4

如何解析多级json?

Json 格式(n 级深):

    [
      {
        "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"
  }
]

例如。我想阅读每个孩子的“身份证”。
我已经尝试过$.each,但这允许我解析固定数量的级别。

4

2 回答 2

7

您需要使用递归

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;
}
于 2013-02-18T08:51:43.350 回答
2

使用 $.each() 并检查每个对象的对象或数组。

  1. 如果对象索引为“id”,则将 id 对象推入结果数组
  2. 如果对象是数组或对象,则递归调用。
  3. 如果没有,请返回。

这是一些代码。工作代码位于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;
}
于 2013-02-18T09:02:53.303 回答