How to verify that one JSON object is present in another

I have two datasets in JSON (data.json) as shown 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 that 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> 

When I click the Submit button, I want to first check whether the entered username (stored in var, say x ) was in the Admins list in my JSON file or not, For example: if x is jhon I want to know if the same exists jhon in Admins JSON .

JavaScript at the moment:

 function finalcheck(){ var x = document.forms["myForm"]["uid"].value; var y = document.forms["myForm"]["pwd"].value; } 

Help with JavaScript is much appreciated!

+5
source share
3 answers

Your loop should go through the JSON object and check for uid or not.

adminFlag will be set to true if x present in Admins .

Try using the code 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; } } } 
+1
source

To check if password the same as the user in JSON, you should encode this JSON array and check the values:

 for (var i = 0; i < UP.length; i++) { if (UP[i].username == x && UP[i].password == y) { for (var j = 0; j < Admins.length; j++) { if (Admin[i].Admin == x) { //It correct logins, do something } } } } 

Security


Never put passwords in a place accessible to the user, always use internal verification, always encode your passwords. Your approach is VERY VERY unsafe. I can always check the source JSON file and see what logins I can enter to log in as admin

+2
source

I believe this task is for learning. Never do this in production. You can play with this sample code. There are many reasonable solutions, but in my opinion, this will help you understand the basics.

 var UP = [{"password": "jhonjhon", "username":"jhon"}, {"password": "juliejulie", "username":"julie"}, {"password": "blakeblake", "username":"blake"}]; var ADMINS = [{"Admin":"jhon"}, {"Admin":"julie"}]; function finalcheck() { var x = 'jhon'; var y = 'jhonjhon'; for(var i = 0; i < UP.length; i++) { if (UP[i].password == x && UP[i].username == y) { console.log(y + ' has access!'); for (var j = 0; j < ADMINS.length; j++) { if (ADMINS[j].Admin == y) { console.log(y + ' is Admin'); } } } } } 
+1
source

All Articles