2016-07-14 19 views
0

Brauchen Sie Hilfe beim Parsen von JSON-Datei. Ich muss 'Auswahl' aus der Datei unten extrahieren.Json Parsing Nodejs

{"questions":[ 
    {"question1": "Who is Prime Minister of the United Kingdom?", "choices":  ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], "correctAnswer":0}, 
    {"question": "North West", "choices": ["What is the name of Kim Kardashian's baby?", "What is the opposite of south?"], "correctAnswer":0}, 
    {"question": "What's my favorite color?", "choices": ["Black", "Blue", "Magenta", "Red"], "correctAnswer":1}, 
    {"question": "What's the meaning of life?", "choices": ["Too live happily", "To give to the greater good"], "correctAnswer":1} 
]} 

NodeJS Skript:

var fs = require("fs"); 
fs.readFile(__dirname + "/lib/questions.json", "Utf-8", function(err, data){ 
jsoncontent = JSON.parse(data); 
//console.log(jsoncontent); 

for (var i = 0; i < jsoncontent.length; ++i) { 
//code 

} 

}); 

Wie zu extrahieren?

+1

definieren 'extract' in Bezug auf die erwarteten Ergebnisse zeigt. Zeigen Sie auch den Code an, mit dem Sie versucht haben, dies selbst zu lösen. Dies ist kein Code-Schreibdienst und es wird erwartet, dass Sie Ihre Versuche zeigen. – charlietfl

Antwort

0

versuchen, wie diese

var choiceList; 
for (var i = 0; i < jsoncontent["questions"].length; ++i) { 
    //do what ever you want with choices 
    choiceList = jsoncontent["questions"][i]["choices"]; 
    console.log(choiceList); 
} 
+0

Ich habe dich nicht verstanden, denke ich. Sie können hier sehen, es gibt Ihnen jede Zeile über die gesamte Schleife –

0
const choices = jsoncontent.questions.map(q => q.choices); 

, die Sie mit nur den "Auswahl" Eigenschaften ein Array geben.

jsoncontent.questions.forEach(q => console.log(q)); 

Das wird "Auswahlmöglichkeiten" ausdrucken.

const jsoncontent = { 
 
    "questions":[ 
 
    { 
 
     "question1": "Who is Prime Minister of the United Kingdom?", 
 
     "choices": ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], 
 
     "correctAnswer":0 
 
    }, 
 
    { 
 
     "question": "North West", 
 
     "choices": ["What is the name of Kim Kardashian's baby?", "What is the opposite of south?"], 
 
     "correctAnswer":0 
 
    }, 
 
    { 
 
     "question": "What's my favorite color?", 
 
     "choices": ["Black", "Blue", "Magenta", "Red"], 
 
     "correctAnswer":1 
 
    }, 
 
    { 
 
     "question": "What's the meaning of life?", 
 
     "choices": ["Too live happily", "To give to the greater good"], 
 
     "correctAnswer":1 
 
    } 
 
]} 
 

 
const choices = jsoncontent.questions.map(q => q.choices); 
 
console.log(choices); 
 

 
jsoncontent.questions.forEach(q => console.log(q));