【问题标题】:how to read multi-levels json format using jquery如何使用 jquery 读取多级 json 格式
【发布时间】:2013-03-27 11:55:17
【问题描述】:

我有一个类似的json格式

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

我使用像print json_encode($rows);这样的php
我尝试在客户端使用 jquery 来阅读它

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

但它不起作用。我该怎么做?谢谢

【问题讨论】:

    标签: php jquery json


    【解决方案1】:

    如果您的代码正常工作,您可能会收到以下错误:

    TypeError: obj is undefined
    

    这是因为外部数组中的第一个对象没有“da”属性的值。在尝试遍历“da”属性持有的数组之前,您应该检查它是否存在。

    试试:

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

    【讨论】:

      【解决方案2】:
       $.each(json, function(arrayID, arrayVal) {
        //alert(arrayVal.id);
        $.each(arrayVal.da, function(daKey,daData) {
         alert(daData.kc);
        });
       });
      

      这是我不久前的相同 SO 问题,以获取更多代码

      JQuery $.each() JSON array object iteration

      编辑以重命名一些变量以使其更清晰

      【讨论】:

      • 每次遇到json数组中的“kc”节点值时都应该提示,如果提示是alert(arrayVal.id+daData.kc) 会显示第一个each+kc的id节点嵌套节点值等
      • 谢谢大家,但它不适合我。我尝试@john S 的回答,它的工作原理:)
      【解决方案3】:

      对于 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 parseJsonString(data){       
          $.each(data, function(index, val){
      
              if($.type(val) == 'object' || $.type(val) == 'array'){
                  product.parseJsonString(val);
              }else{
                  alert(index + ' - ' + val);
              }
      
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-12
        • 2012-11-10
        • 2013-05-30
        • 2011-07-02
        • 1970-01-01
        相关资源
        最近更新 更多