Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing multi-level JSON [duplicate]

How to parse multilevel 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"
  }
]

for eg. I want to read every children "id".
I have tried $.each but that allows me to parse fixed number of levels.

like image 238
Ashwin Avatar asked Jan 14 '23 04:01

Ashwin


1 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;
}
like image 130
sigod Avatar answered Jan 16 '23 21:01

sigod