在json中循环 - jquery

时间:2012-02-28 10:16:57

标签: jquery json

{
"info": {
    "limit": "0",
    "xdata": {
        "hospital": {
            "name": "qwewe",
            "street": "cxcxc"
        },
        "factory": {
            "name": "wrwr",
            "street": "xzcc"
        },
        "industry": {
            "name": "lll",
            "street": "sdfdsfdf"
        }
    }
    }

如何打印xdata的内容?我想要医院,工厂和工厂的数据。行业 我正在使用$.each jQuery循环,但无法将详细信息提供给医院。

5 个答案:

答案 0 :(得分:6)

var data = {
"info": {
    "limit": "0",
    "xdata": {
        "hospital": {
            "name": "qwewe",
            "street": "cxcxc"
        },
        "factory": {
            "name": "wrwr",
            "street": "xzcc"
        },
        "industry": {
            "name": "lll",
            "street": "sdfdsfdf"
        }
    }
}};

$.each(data.info.xdata, function(key, value) {
    var type = key; // e.g. hospital/factory/industry
    var name = value.name;
    var street = value.street;

    // do something with the values
    console.log(type, name, street);
});

喜欢这个?说实话,JSON并没有真正的格式化。 XDATA最好包含一个对象数组,但是meh。

有关更多信息,请参阅此jsfiddle:http://jsfiddle.net/fZBYG/1/请务必打开控制台。

答案 1 :(得分:3)

尝试下一步

xdata = your_data.info.xdata;

for (xd in xdata) {
  console.log('Name: ' + xdata[xd].name);
  console.log('Street: ' + xdata[xd].street);
}

答案 2 :(得分:2)

希望这会对你有帮助 - http://jsfiddle.net/ZE47n/7/

答案 3 :(得分:1)

$.each(info.xdata, function(key, value) {
    // key is equal to hospital, factory, industry
    // valus is equal to { "name": "qwewe", "street": "cxcxc" }, ...
    // this in the scope is the same as arguments[1] - value;
    // this === value
});

答案 4 :(得分:1)

var json = $.parseJSON(j);
//console.log(json.info.xdata);
$.each(json.info.xdata,function(k,v){
console.log(v.name+" -- "+ v.street);
});

DEMO