Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON with number as a key

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

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

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.

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.

like image 299
Caimen Avatar asked May 08 '14 21:05

Caimen


People also ask

Can a number be a key in JSON?

Keys must be strings, and values must be a valid JSON data type: string. number.

Can JSON values be numbers?

In JSON, values must be one of the following data types: a string. a number. an object (JSON object)

How do I key a JSON?

JSON keys are on the left side of the colon. They need to be wrapped in double quotation marks, as in "key" , and can be any valid string. Within each object, keys need to be unique.


1 Answers

You need to use bracket notation:

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

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

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

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.

like image 145
p.s.w.g Avatar answered Sep 21 '22 20:09

p.s.w.g