Ho il seguente codice, purtroppo non ho alcun controllo su questa uscita.Come analizzare JSON con il numero come chiave
{
"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"
}
}
}
}
Sto usando json.parse per analizzare questo. Per ottenere il testo della prima domanda normalmente farei qualcosa di simile.
var jsonData = JSON.parse(data);//Where data = the json above
console.log(jsonData.questions.9733.text);//Obviously this fails
Tuttavia javascript non piace quel numero in là ovviamente. Come consiglieresti di accedere al testo della prima domanda? Preferirei che il json fosse configurato meglio con una serie di domande. Sfortunatamente non ho alcun controllo sull'output di questo JSON.
Inoltre, non mi accorgo di quali sono le chiavi mentre si imbattono, ma questo è un altro problema. Sono disposto ad intrattenere qualsiasi suggerimento su come analizzare questa cosa come non ho mai dovuto analizzare una tale uscita JSON così strana.
Vorrei solo usare 'jsonData [ 'domande'] [ '9733'] [ 'testo']' ' – NullUserException
jsonData.questions [9733] .text' dovrebbero funzionare. 'foo.bar' e' foo ['bar'] 'sono equivalenti in JS. – IMSoP