我有这个json文件,我正在变成一个json数组,一切正常,但真正的json文件包含更多数据。 如何简化此代码可以更改javascript或json文件。
{
"Subject1":{
"Biology":{
"Category":{
"Cell":{
"question1":{
"que1":"what's....?"
},
"question2":{
"que2":"what's....?"
},
"question3":{
"que3": "what's....?"
}
},
"Bactery":{
"question1":{
"que1":"what's....?"
},
"question2":{
"que2": "what's....?"
},
"question3":{
"que3": "what's....?"
}
}
}
}
}
}
这是我的代码女巫将文件json转换为javascript的数组json:
var exa = [];
function show() {
$.getJSON('questions.json', function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
exa.push({
//I want to simplify this part, because the real json file have more questions
que1: item.Biology.Category.Cell.question1.que1,
que2: item.Biology.Category.Cell.question2.que2,
que3: item.Biology.Category.Cell.question3.que3,
que11: item.Biology.Category.Bactery.question1.que1,
que12: item.Biology.Category.Bactery.question2.que2,
que13: item.Biology.Category.Bactery.question3.que3
});
}
}
//return Books;
console.log(exa)
})
}
答案 0 :(得分:1)
而不是que1,que2等,只是在数组中有问题
"Cell": [
"what's this?",
"what's that?"
]
答案 1 :(得分:0)
您可以使用json-path并撰写JsonPath.read(json, "$..question");
来解答所有问题。您还需要将文件中的所有que[*]
更改为question
。