簡體   English   中英

如何訪問 JSON 對象中的數組?

[英]How to access an array in a JSON object?

我有以下 JSON 對象:

[
    {
        "comments": [
            {
                "created_at": "2011-02-09T14:42:42-08:00",
                "thumb": "xxxxxxx",
                "level": 1,
                "id": 214,
                "user_id": 41,
                "parent_id": 213,
                "content": "<p>xxxxxx</p>",
                "full_name": "xx K"
            },
            {
                "created_at": "2011-02-09T14:41:23-08:00",
                "thumb": "xxxxxxxxxxxxx",
                "level": 0,
                "id": 213,
                "user_id": 19,
                "parent_id": null,
                "content": "<p>this is another test</p>",
                "full_name": "asd asd asd asd asd"
            }
        ],
        "eee1": "asdadsdas",
        "eee2": "bbbbb"
    }
]

這是來自$.ajax請求,我成功了....

success: function (dataJS) {
    console.log(dataJS);
    console.log(dataJS[eee1]);
    console.log(dataJS.comments);
}

問題是我無法訪問 JSON 對象中的項目,即使 dataJS 確實在控制台中正確顯示。 想法?

那是因為您的基礎對象也是一個數組。

console.log(dataJS[0].comments[0]);

我懷疑這會起作用

你回來的 JSON 實際上是一個數組本身,所以......

dataJS[0].comments[0].created_at

將是2011-02-09T14:42:42-08:00等...

dataJScomments都是數組,需要索引來訪問適當的元素。

返回的對象本身就是一個數組,因此要獲得第一個注釋(作為示例),您可以通過以下方式訪問它:

dataJS[0].comments[0]

console.log(dataJS);
console.log(dataJS[0].eee1);
console.log(dataJS[0].comments[0]);

做這樣的事情: -

var dataJS = [{"comments":[{"created_at":"2011-02-09T14:42:42-08:00","thumb":"xxxxxxx","level":1,"id":214,"user_id":41,"parent_id":213,"content":"<p>xxxxxx</p>","full_name":"xx K"},{"created_at":"2011-02-09T14:41:23-08:00","thumb":"xxxxxxxxxxxxx","level":0,"id":213,"user_id":19,"parent_id":null,"content":"<p>this is another test</p>","full_name":"asd asd asd asd asd"}],"eee1":"asdadsdas","eee2":"bbbbb"}];

var created_at = dataJS[0].comments[0].created_at;

是的,正如其他人所說,JSON 實際上是一個數組(單個對象的)。 所以你需要引用一個索引。

有趣的是(對我而言),您的結果字符串確實成功驗證為 JSON。 到目前為止,我一直認為,要成為有效的 JSON,它必須是一個對象(即 {})。

您必須將 ajax 請求中的 dataType 稱為“JSON”。 讓用戶像下面那樣做。

 $.ajax({
            url: $('#frmAddCourse').attr('action'),
            type: 'POST',
            data: $('#frmAddCourse').serialize(),
            dataType: 'JSON',
            success: function (data){
                Materialize.toast(data['state'],2000);
            },
            error:function(){
                Materialize.toast(errorMessage,2000);
            }
        });

JSON 必須用eval函數解釋(在明顯的清理之后,請參閱 eval 的安全注意事項)。 您確定您的框架可以為您做到這一點嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM