【问题标题】:How to parse a JSON file in javascript without having any knowledge about the contents of the file? [duplicate]如何在不了解文件内容的情况下用 javascript 解析 JSON 文件? [复制]
【发布时间】:2015-07-07 20:40:38
【问题描述】:

我想知道如何解析任何 JSON 文件而不考虑内容。 例如,我必须解析以下 JSON。如何在不使用 JSON 文件中的单词/键的情况下解析它并调用值?

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"
}]

【问题讨论】:

  • 您必须对其进行迭代,否则您无法知道键或索引是否存在
  • 或者使用eval()将它变成一个对象?
  • Object.keys() 可能会有所帮助

标签: javascript json parsing key


【解决方案1】:

您将需要一个循环来遍历 a 中的每个元素,并需要一个循环来遍历对象中的每个键。 (此外,您在第一个对象中的前缀和基数之间缺少逗号)

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]);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    相关资源
    最近更新 更多