Jeremy G Jeremy G - 4 months ago 12
JSON Question

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!

Answer

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>