Yahya Alami Yahya Alami - 4 months ago 11
JSON Question

How to read a complex and nested json data

My question is, how can you read a specefic form of json data using javascript, for example if i had this one, it's seems to me a bet difficult, so can you help me out.

{
"jQRReponse": [
[
{
"sujet": "RHONE ALPES",
"verbe": "est_le_nom_de_la_region",
"complement": {
"sujet": "82",
"verbe": "est_la_region_du_dept",
"complement": {
"sujet": "01",
"verbe": "est_le_numero_du_dept",
"complement": {
"sujet": "Ain",
"verbe": "contient_les_resultats_de_depAnn",
"complement": {
"sujet": "Ain2014",
"verbe": "Pop_results_Ens_Total",
"complement": "626794"
}
}
}
}
}
],
[
{
"sujet": "RHONE-ALPES",
"verbe": "est_le_nom_de_la_region",
"complement": {
"sujet": "82",
"verbe": "est_la_region_du_dept",
"complement": {
"sujet": "01",
"verbe": "est_le_numero_du_dept",
"complement": {
"sujet": "Ain",
"verbe": "contient_les_resultats_de_depAnn",
"complement": {
"sujet": "Ain2014",
"verbe": "Pop_results_Ens_Total",
"complement": "626794"
}
}
}
}
}
]
]
}


Say if I had this form:

data : [{
toto:5,
mama:10
},
{
toto:99,
mama:10
},
{
toto:88,
mama:10
}]


I'm gonna read the toto value at the index i like this :
data[i].toto
.

So how can I do it for the first one.

Thank you

Answer

You could iterate over all data and get the ressult.

The access is in the form like

data.jQRReponse[0][0].complement.complement.sujet
// returns "01"

function read(o) {
    Object.keys(o).forEach(function (k) {
        if (o[k] !== null && typeof o[k] === 'object') {
            console.log(k + ' -->');
            read(o[k]);
            return;
        }
        console.log(k + ': ' + o[k]);
    });
}

var data = { "jQRReponse": [[{ "sujet": "RHONE ALPES", "verbe": "est_le_nom_de_la_region", "complement": { "sujet": "82", "verbe": "est_la_region_du_dept", "complement": { "sujet": "01", "verbe": "est_le_numero_du_dept", "complement": { "sujet": "Ain", "verbe": "contient_les_resultats_de_depAnn", "complement": { "sujet": "Ain2014", "verbe": "Pop_results_Ens_Total", "complement": "626794" } } } } }], [{ "sujet": "RHONE-ALPES", "verbe": "est_le_nom_de_la_region", "complement": { "sujet": "82", "verbe": "est_la_region_du_dept", "complement": { "sujet": "01", "verbe": "est_le_numero_du_dept", "complement": { "sujet": "Ain", "verbe": "contient_les_resultats_de_depAnn", "complement": { "sujet": "Ain2014", "verbe": "Pop_results_Ens_Total", "complement": "626794" } } } } }]] };

read(data, []);

Comments