我有以下json,遗憾的是我对这个输出没有任何控制权.
{
"questions": {
"9733": {
"text": "Star Trek or Star Wars?",
"answers": {
"41003": "Star Trek",
"41004": "Star Wars",
"41005": "Neither is superior in my opinion; both great in their own ways",
"41006": "Not a fan",
"41007": "I don't have an opinion on this"
}
},
"25272": {
"text": "Which of these summer movies are you looking forward to the most?",
"answers": {
"99545": "World War Z",
"99546": "Monsters University ",
"99547": "White House Down",
"99548": "Man of Steel",
"99549": "Lone Ranger",
"99550": "The Wolverine"
}
},
"27547": {
"text": "Should the U.S. attack Syria?",
"answers": {
"107453": "Yes",
"107454": "No"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用json.parse来解析它.要获得第一个问题的文本,我通常会做这样的事情.
var jsonData = JSON.parse(data);//Where data = the json above
console.log(jsonData.questions.9733.text);//Obviously this fails
Run Code Online (Sandbox Code Playgroud)
但是javascript显然不喜欢那个数字.您如何建议访问第一个问题的文本?我宁愿在一系列问题中更好地设置json.不幸的是,我对这个JSON的输出没有任何控制权.
我也不会意识到它们遇到的键是什么,但那是另一个问题.我愿意接受有关如何解析这个东西的任何建议,因为我从来没有必要解析这样一个奇怪的JSON输出.
p.s*_*w.g 10
您需要使用括号表示法:
console.log(jsonData.questions["9733"].text);
Run Code Online (Sandbox Code Playgroud)
但是因为括号内的值会自动转换为字符串,所以这也可以:
console.log(jsonData.questions[9733].text);
Run Code Online (Sandbox Code Playgroud)
但是请注意,使用非字符串作为属性名称一般状态不佳,并可能导致一些微妙的问题,例如,如果属性名称是"001",那么[001]就不会工作.
| 归档时间: |
|
| 查看次数: |
11046 次 |
| 最近记录: |