如何检查另一个存在的JSON对象 [英] How to check for one JSON object being present in another
问题描述
我在 JSON (data.json)中有两组数据,如下所示:
UP = [{password:jhonjhon,username:jhon},{password:juliejulie,username:julie},{password:blakeblake用户名 : 布莱克}];
和
Admins ='[{Admin:jhon},{Admin:julie}]';
我有一个 HTML 表单,用户将使用它登录。
< html>
< body>
UserName< input type =textid =uidvalue =UserId/>
UserPassword< input type =passwordid =pwdvalue =UserPwd/>
< input type =submit/>
< / form>
< / body>
< script src =data.json>< / script>
< script src =checking.js>< / script>
< / html>
点击提交按钮,我想先检查用户名(存储在var,例如 x
)是否属于 JSON 文件中的 Admins
列表。例如:如果 x
是 jhon
我想知道相同的 jhon
存在于 JSON 的 Admins
中。
截至目前的JavaScript
如下: function finalcheck(){
var x = document.forms [myForm] [uid] .value;
var y = document.forms [myForm] [pwd] .value;
}
非常感谢JavaScript的帮助!
<您应该循环遍历JSON对象并检查
uid
是否存在。如果 x
是 $ b
adminFlag
出现在 Admins
。 尝试下面给出的代码:
function finalCheck(){
var adminJSON = JSON.parse(Admins),//因为Admins是字符串,所以先解析为Json
length = adminJSON。长度,
x = document.forms [myForm] [uid]。value,
y = document.forms [myForm] [pwd]。value,
adminFlag =假;
// for for循环找到admin是否存在
for(var i = 0; i< length; i ++){
if(adminJSON [i] .Admin == x){
adminFlag = true;
休息;
}
}
}
I have two sets of data in a JSON (data.json) as below :
UP = [{"password": "jhonjhon", "username":"jhon"}, {"password": "juliejulie", "username":"julie"}, {"password": "blakeblake", "username":"blake"}];
And
Admins = '[{"Admin":"jhon"}, {"Admin":"julie"}]';
I have an HTML form which the user will use to login.
<html>
<body>
<form name="myForm" onsubmit="finalCheck()">
UserName<input type="text" id="uid" value="UserId"/>
UserPassword<input type="password" id="pwd" value="UserPwd"/>
<input type="submit"/>
</form>
</body>
<script src="data.json"></script>
<script src="checking.js"></script>
</html>
On the click of the submit button I want to first check if the username (stored in a var, say x
) entered belongs to the Admins
list in my JSON file or not. Eg: if x
is jhon
I want to know if the same jhon
exists in the Admins
of the JSON.
JavaScript as of now is as :
function finalcheck(){
var x = document.forms["myForm"]["uid"].value;
var y = document.forms["myForm"]["pwd"].value;
}
Help with JavaScript is much appreciated!
Your should loop through the JSON object and check the uid
is present or not.
adminFlag
will set to true if the x
is present in Admins
.
Try the code given below:
function finalCheck(){
var adminJSON = JSON.parse(Admins), // since Admins is string, parse to Json first
length = adminJSON.length,
x = document.forms["myForm"]["uid"].value,
y = document.forms["myForm"]["pwd"].value,
adminFlag = false;
// for loop to find admin is present or not
for(var i = 0; i < length; i++){
if(adminJSON[i].Admin == x){
adminFlag = true;
break;
}
}
}
这篇关于如何检查另一个存在的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!