迭代JSON结果

时间:2013-11-16 19:08:37

标签: jquery xml json

我使用插件将XML(http://gyazo.com/fe38f0eb89a1f1f88927f676f304cc1c)解析为JSON。 我希望它循环遍历所有类别,并且对于每个循环周期重复子类别和道具的过程,它应该通过循环无限地执行此操作。

我已经查看了递归函数,这是我正在尝试的但是它不适合我,因为console.log总是说我的$ .each获取子元素时它是未定义的。

JQuery的

function ParseData(v) {
    var caption = v.caption;
    console.log('Category ' + caption + ' parsed.');

    if (v.prop != undefined) {
        console.log('Prop(s) found, parsing....');
        $.each(v.prop, function(key, value) {
            ParseData(v.prop);
        });
    }
    else if (v.cat != undefined) {
        console.log('Child(s) found, parsing....');
        $.each(v.cat, function(key, value) {
            ParseData(v.cat);
        });
    }
}


function loadProps() {
    //variables
    var pb = $('div#prop_browser');

    //parse prop categories
    console.log('Parsing Categories....');
    $.get("prop-cat.xml", function(xml) {
        var data = $.xml2json(xml);
        $.each(data, function(key, value) {
            $.each(value, function(key, value) {
                ParseData(value);
            });
        });
    });
}

我真的花了几个小时的谷歌搜索和编码,但我无法弄清楚这一点,我怀疑这是我的逻辑......

请帮助我!

示例JSON(使用JSON.stringify而不是ParseData): 第一个JSON字符串有两个类别,一个道具。 第二个JSON字符串有一个类别和一个prop。

{"cat":[{"id":"0","caption":"Dog 1","img":""},{"id":"0","caption":"Dog 9","img":""}],"prop":{"caption":"Prop 1","img":""},"id":"0","caption":"Cat 1","img":""}

{"cat":{"id":"0","caption":"Dog 1","img":""},"prop":{"caption":"Prop 2","img":""},"id":"0","caption":"Cat 2","img":""}

@ charlietfl的JSFiddle,无法正常工作!

function processData() {
    $(pb).append('<div class="prop_category">' + $(this).attr('caption'));
    if ($(this).children().length > 0) {
        $(this).children().each(processData);
    } else {
        $(pb).append('</div>');
    }
}

function loadProps() {
    //variables
    pb = $('#prop_browser');

    $.get("prop-cat.xml", function(xml) {
        $(xml).children().each(processData);
    });
}

0 个答案:

没有答案
相关问题