Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten nested JSON?

Let's say I am dealing with JSON like this:

http://hndroidapi.appspot.com/nestedcomments/format/json/id/4620423?appid=hntoolbar&callback=

Which can be infinitely nested. I want to extract all of the comment information in a "flattened" format, just a list of usernames and the contents of their comment without worrying about the "level" of the comment. How would I do something like that using Javascript/JQuery?

like image 741
Sam Stern Avatar asked Sep 04 '26 13:09

Sam Stern


1 Answers

use recursion:

var getall = function(comments,out) {
    var out = out || {};
    var cuser = undefined;
    var comment;
    for (var key in comments) {
        if (key == 'username') {
            cuser = comments[key];
            continue;
        }
        if (key == 'comment') {
            comment = comments[key];
            continue;
        }
        var mytype = typeof(comments[key]);
        if (mytype == 'object'
        || mytype == 'array') {
            out=getall(comments[key],out);
        };
    }
    if (cuser !== undefined) {
        if (out[cuser] === undefined) {
            out[cuser] = [];
        }

       out[cuser].push(comment);
    }
    return (out);
}
b=getall(a);
console.log(b);​

a here - parsed JSON, b - result;

b structure is

{user1: [comment,comment,comment],user2: [] ...}

http://jsfiddle.net/NkTst/1/

check http://jsfiddle.net/NkTst/2/ if you still need extended info on comments

like image 64
zb' Avatar answered Sep 07 '26 01:09

zb'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!