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

时间:2022-07-04 11:46:04

I have this json file, and I'm turning into a json array, everything works fine, but the real json file contains more data. How to simplify this code could either change the javascript or json file.

我有这个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....?"
                }
            }
        }
    }
}

}

}

this is my code witch convert the file json into array json of javascript:

这是我将文件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)
    })
}

2 个解决方案

#1


1  

Instead of que1, que2, etc., just have the questions in an array

而不是que1, que2,等等,只是在数组中有问题。

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

#2


0  

You can use json-path and write JsonPath.read(json, "$..question"); to get all questions. You need to change all que[*] in your file to question too.

您可以使用json-path并编写JsonPath。读(json,“美元…问题”);把所有的问题。您还需要更改文件中的所有que[*],以便查询。

#1


1  

Instead of que1, que2, etc., just have the questions in an array

而不是que1, que2,等等,只是在数组中有问题。

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

#2


0  

You can use json-path and write JsonPath.read(json, "$..question"); to get all questions. You need to change all que[*] in your file to question too.

您可以使用json-path并编写JsonPath。读(json,“美元…问题”);把所有的问题。您还需要更改文件中的所有que[*],以便查询。