如何使用数字作为键解析JSON [英] How to parse JSON with number as a key

查看:105
本文介绍了如何使用数字作为键解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json,很遗憾,我对此输出没有任何控制.

I have the following json, I don't have any control over this output unfortunately.

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

我正在使用json.parse对此进行解析.为了获得第一个问题的文本,我通常会这样做.

I am using json.parse to parse this. To get the text of the first question I would normally do something like this.

var jsonData = JSON.parse(data);//Where data = the json above
console.log(jsonData.questions.9733.text);//Obviously this fails

但是,javascript很明显不喜欢那里的那个数字.您如何建议访问第一个问题的文本?我宁愿在一系列问题中更好地设置json.不幸的是,我对此JSON的输出没有任何控制.

However javascript doesn't like that number in there obviously. How would you recommend accessing the text of the first question? I would prefer the json to be setup better with in an array of questions instead. Unfortunately I don't have any control over the output of this JSON.

我也不会知道它们遇到的键是什么,但这就是另一个问题.我愿意就如何解析此事物提供任何建议,因为我从未必须解析过如此奇怪的JSON输出.

I'm also not going to be aware of the what the keys are as they come across, but thats a whole other issue. I'm willing entertain any suggestions on how to parse this thing as I've never had to parse such a strange JSON output.

推荐答案

您需要使用

但是由于括号内的值将自动转换为字符串,因此也可以:

But because the value inside the brackets will be automatically converted a string, this would also work:

console.log(jsonData.questions[9733].text);

但是请注意,使用非字符串作为属性名称通常是错误的形式,并可能导致一些细微的问题,例如如果属性名称为"001",则[001]起作用.

Note however, that using non-strings is as property names generally bad form and could lead to some subtle problems, e.g. if the property name was "001", then [001] would not work.

这篇关于如何使用数字作为键解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆