How to parse a JSON file in javascript without hav

2019-03-04 12:48发布

问题:

This question already has an answer here:

  • Access / process (nested) objects, arrays or JSON 20 answers

I would like to know how to parse any JSON file irrespective of the contents. For example, I have to parse the following JSON. How would I parse it and call values without using words/keys from the JSON file?

var a = [{
    "Master Row": "P558:15",
    "Prefix*": "5C34",
    "Base*": "1508",
    "Suffix*": "CA",
    "Weight Unit of Measure": "lb"
}, {
    "Master Row": "P558:16",
    "Prefix*": "5C34",
    "Base*": "1508",
    "Suffix*": "CA",
    "Weight Unit of Measure": "lb"
}]

回答1:

You will need a loop to go through each element in a, and a loop to go through each key in the objects. (Also you are missing a comma between prefix and base in the first object)

var a= [ { "Master Row":"P558:15", "Prefix*":"5C34","Base*":"1508", "Suffix*":"CA", "Weight Unit of Measure":"lb" }, { "Master Row":"P558:16", "Prefix*":"5C34", "Base*":"1508", "Suffix*":"CA", "Weight Unit of Measure":"lb" } ];

for(i=0;i<a.length;i++){
  var temp=a[i];
  for(key in temp){
    console.log(key+' '+temp[key]);
  }
}