如何简化此代码?将文件json转换为数组json

How I can simplify this code? convert file json to array json

本文关键字:json 转换 数组 文件 何简化 代码      更新时间:2023-09-26

我有这个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)
    })
}

不要使用que1、que2等,只需将问题放入数组中即可

"Cell": [
    "what's this?",
    "what's that?"
]

您可以使用json路径并编写JsonPath.read(json, "$..question");来获取所有问题。您还需要将文件中的所有que[*]更改为question