简体   繁体   中英

javascript accessing nested json

I'm working with nested json files like the following: https://dl.dropboxusercontent.com/u/98561379/output.json

In the above file, I am trying to access all the objects that have "size": 1 as a value and append the "canonical" array that is in the same object to an array. So for the above example, the output would be an array containing 9 unique "canonical" arrays. So far I have unsuccessfully tried to use recursion.

function recursive(json){
    var arr = [];

    if (json.size == 1){
        arr.push(json.canonical)
    } else {
        recursive(json.left)
    }
    return arr;
}

Any help is appreciated. Thanks!

You can use this:

var json = "";
var data = [];

function recursive(json) {
    if (json.size === 1) {
        data.push(json.canonical);
    }
    if (json.left) {
        recursive(json.left);
    }
    if (json.right) {
        recursive(json.left);
    }
}
//Let's start
recursive(json);
//the result
console.log(data);

Demo:

 $.get("https://dl.dropboxusercontent.com/u/98561379/output.json", function(resp) { var json = JSON.parse(resp); var data = []; (function find(json) { if (json.size === 1) { data.push(json.canonical); } if (json.left) { find(json.left); } if (json.right) { find(json.left); } })(JSON.parse(resp)); console.log(JSON.stringify(data)); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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