简体   繁体   English

如何使用jQuery读取多级json格式

[英]how to read multi-levels json format using jquery

i have a json format like 我有一个像json格式

[
    {
        id: 15,
        diemdung: "a"
    },
    {
        id: "16",
        diemdung: "b",
        khoangcach: "300",
        pho: "c",
        da: [
            {
                lancan: "d",
                kc: "333"
            },
            {
                lancan: "e",
                kc: "322"
            }
        ]
    },
    ...
]

i using php like print json_encode($rows); 我使用类似print json_encode($rows);
and i try to read it at client using jquery like 而且我尝试使用jquery在客户端读取它

$.getJSON(url,function(json){
    $.each(json,function(key, val){
        $.each(this.da,function(){
            alert(this.kc);
        });
    });
});

but it's not working. 但它不起作用。 How i do that? 我该怎么做? thanks 谢谢

If your code is otherwise working, you may be getting the following error: 如果您的代码可以正常工作,则可能会出现以下错误:

TypeError: obj is undefined

This is because the first object in the outer array does not have a value for the "da" property. 这是因为外部数组中的第一个对象没有“ da”属性的值。 Before you try to loop over the array held by the "da" property, you should check if it exists. 在尝试遍历由“ da”属性持有的数组之前,应检查它是否存在。

Try: 尝试:

$.getJSON(url,function(json){
    $.each(json,function(){
        if (this.da) {
            $.each(this.da,function(){
                alert(this.kc);
            });
        }
    });
});
 $.each(json, function(arrayID, arrayVal) {
  //alert(arrayVal.id);
  $.each(arrayVal.da, function(daKey,daData) {
   alert(daData.kc);
  });
 });

Heres my same SO question a while ago for further code 不久前这是我的同样问题,以获取更多代码

JQuery $.each() JSON array object iteration jQuery $ .each()JSON数组对象迭代

edit to rename some variables to make clearer 编辑以重命名一些变量以使其更清晰

For n level hierarchy 对于n级层次结构

var str = '{"countries":[{"name":"USA","grandfathers":[{"gFName":"Steve","grandfathersKid":[{"gFKName": "Linda","kid": [{"name": "Steve JR", "friends": [{"name": "Kriss|John|Martin|Steven"}]}]}]}]}]}';
var obj = jQuery.parseJSON(str);
parseJsonString(obj);

Function : 功能说明

function parseJsonString(data){       
    $.each(data, function(index, val){

        if($.type(val) == 'object' || $.type(val) == 'array'){
            product.parseJsonString(val);
        }else{
            alert(index + ' - ' + val);
        }

    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM