我如何使用javascript和jquery获取json文件的数组json
我正在尝试下一个代码,它不起作用:
var questions = []; function getArray(){ $.getJSON('questions.json', function (json) { for (var key in json) { if (json.hasOwnProperty(key)) { var item = json[key]; questions.push({ Category: item.Category }); } } return questions; }) }
这是一个名为的json文件:questions.json
{ "Biology":{ "Category":{ "cell":{ "question1":{ "que1":"What is the cell?" }, "option1":{ "op1":"The cell is the basic structural and functional unit", "op2":"is a fictional supervillain in Dragon Ball" }, "answer1":"opt1" } } }, "Astronomy":{ "Category":{ "Mars":{ "question1":{ "que1":"How many moons does Mars?" }, "option1":{ "op1":"5", "op2":"2" }, "answer1":"opt2" } } } }
我想要一个具有以下格式的数组{Biology:{Category:{cell:{question1 ....}}}}
$.getJSON是一个异步函数,因此返回该函数内部的任何内容均无济于事,因为它不在范围内或尚未收到。您可能应该执行以下操作:
$.getJSON
function getArray(){ return $.getJSON('questions.json'); } getArray().done(function(json) { // now you can use json var questions = []; $.each(json, function(key, val) { questions[key] = { Category: val.Category }; }); });