【问题标题】:How to read deeper hierarchy json by getJSON如何通过 getJSON 读取更深层次的 json
【发布时间】:2012-07-02 13:49:17
【问题描述】:

Jquery getJSON 函数有点问题。

我的json在这里

{ "entries": [
    {
        "type": "status",
        "SID": "X999_Y999",
        "from": {
            "name": "Tom Brady",
            "id": "X12"
        },
        "message": "Json message no 1! ",
        "actions": {
            "UP_link": "123456",
            "Comment_link": "7891011"
        },
        "created_time": "2010-08-02T21:27:44+0000",
        "Comments": [
            {
                "CID": "1234",
                "name": "Tom Brady",
                "UID": "1234",
                "Text": "My comment",
                "when_comment": "2010-08-02T21:27:44+0000"
            },
            {
                "CID": "1234",
                "name": "Tom Brady",
                "UID": "1234",
                "Text": "My comment",
                "when_comment": "2010-08-02T21:27:44+0000"
            }
        ]
    }
] }

我用这个来阅读

$.getJSON('json4test.json',
    function(data) {            
        $.each(data.entries, function(entryIndex, entry) {
        var html = '<li class="top-level">name=' + this.from.name +', comment = '+this.Comments.Text+ '</li>';
        $("#results").append(html);
        });
    });

我其实可以读取this.from.name的数组,但是为什么读取this.Comments.Text的结果是“未定义”。

如何正确阅读这篇文章?

【问题讨论】:

    标签: jquery json getjson


    【解决方案1】:

    this.Comments.Text 是一个数组,因此您还需要循环遍历它。

    $.each(this.Comments, [...]);
    

    在循环中,您可以访问每个评论的Textproperty。见the example on jsbin(检查控制台的输出)。

    【讨论】:

    • 非常感谢,我明白了,那我现在更了解 JSON 了 :)
    猜你喜欢
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多