Parsing Layered JSON

How to parse layered json?

Json format (n-level deep):

[ { "attr" : { "id" : "97987" }, "children" : [ { "attr" : { "id" : "97988" }, "children" : [ { "attr" : { "id" : "97992" }, "data" : "tag5" }], "data" : "tag2" }, { "attr" : { "id" : "97993" }, "data" : "tag6" } ], "data" : "tag1" }, { "attr" : { "id" : "97989", }, "children" : [ { "attr" : { "id" : "97990" }, "data" : "tag4" }], "data" : "tag3" } ] 

eg. I want to read every child "id".
I tried $.each , but this allows me to analyze a fixed number of levels.

+4
source share
2 answers

You need to use recursion .

 function get_all_ids(data) { var result = []; $(data).each(function (i, element) { result.push(element.attr.id); if (element.children && element.children.length > 0) { var ids = get_all_ids(element.children); result = result.concat(ids); // or $.merge(result, ids); } }); return result; } 
+6
source

Using $ .each () and checking an object or array for each object.

  • if the index of the object is "id", click the id object in the result array
  • If the object is an array or an object, call it recursively.
  • if not, just return it.

Here is the code. The working code is at http://jsfiddle.net/cwdoh/KKFCZ/

 function getAll( input, target ) { var result = []; function parseData( input, target ) { $.each( input, function ( index, obj ) { if ( index == target ) { result.push( obj ); } else { switch ( $.type( obj ).toLowerCase() ) { case "object": case "array": parseData( obj, target ); break; } } } ); } parseData( data, "id" ); return result; } 
+2
source

All Articles