0

I have a set of data in a JSON file that consists of UserIDs (as keys) and Passwords (values). I want to read the same using JavaScript for validation purposes. My JSON is :

IDsNPass = '[{"A":"A15"},{"B":"B15"},{"C":"C15"}]';

I have an idea about how to access the data using JavaScript as long as the keys in the JSON remain the same. But here, the keys in my JSON are not constant all along. Any help on how to get along with the JavaScript is much appreciated!

TheLuminor
  • 1,411
  • 3
  • 19
  • 34

1 Answers1

1

First of all, your design is not a good format.

If you only have a id-password mapping in on object, you can do like this

var ip = JSON.parse(IDsNPass)

for(var obj in ip) {
  for(var key in obj) {
    console.info(key)
    console.info(obj[key])
  }
}
Eric Zeng
  • 135
  • 5
  • Thanks for your opinion! Any suggestions on what format to save UserNames and Passwords in JSON? @EricZeng – TheLuminor Jul 27 '15 at 09:06
  • `json = [{"password": "abcd", "username":"Jhon"}, {"password": "baostu", "username":"Tom"}]`.... then you can do `json.[0].username` – equivalent8 Jul 27 '15 at 09:13
  • ....if this is for storing login details on your site, don't store plain passwords for real users :) ... compare them via MD5 (https://github.com/blueimp/JavaScript-MD5) or some other hashing strategy in your code – equivalent8 Jul 27 '15 at 09:17
  • Following the format that you suggested, I tried the following format for my **JSON** : json = [{"password": "abcd", "username":"Jhon"}, {"password": "efgh", "username":"Tom"}, {"password": "ijkl", "username": "Julie"}]; And I am trying to access it using **JavaScript** as : for(var key in json){ for(var value in json){ if(json.hasOwnProperty(key)){ if(json.hasOwnProperty(value)){ alert(key + "->" + json[key] + "->" + json[value]); } } } } But this doesn't seem to be working. Any ideas on where im going wrong? @equivalent8 – TheLuminor Jul 27 '15 at 09:31
  • here you go dude https://jsfiddle.net/dsu6ekwy/ ` for(var key in json){ var user = json[key] alert(user.username + " -> " + user.password) } ` – equivalent8 Jul 27 '15 at 10:36
  • Thanks a lot for your help @equivalent8 Much Appreciated! Cheers :) – TheLuminor Jul 27 '15 at 14:12