简体   繁体   中英

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

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.

{
"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:

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM