2016-07-14 3 views
0

Нужна помощь в анализе json-файла. Мне нужно извлечь «выбор» из файла ниже.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 сценарий:

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 

} 

}); 

Как извлечь?

+1

определяют 'extract' в плане показа ожидаемых результатов. Также покажите код, который вы использовали, чтобы попытаться решить это самостоятельно. Это не служба написания кода, и вы должны показать свои попытки. – charlietfl

ответ

0

попробовать, как этот

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

Я не понял, что думаю. вы можете видеть здесь, это дает вам каждую строку по всему циклу –

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

Это даст вам массив только "выбор" свойств.

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

Это напечатает «выборы».

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));