簡體   English   中英

獲取JSON數組中的特定對象

[英]Get specific object in JSON array

我正在嘗試從網絡上托管的JSON文件訪問數據。 JSON的格式如下:

{"markers":[ 
    { 
    "latitude":57.7973333, 
    "longitude":12.0502107, 
    "title":"Angered", 
    "content":"Representing :)" 
    },

    { 
    "latitude":57.6969943, 
    "longitude":11.9865, 
    "title":"Gothenburg", 
    "content":"Swedens second largest city" 
    } 
]
"markersupdate": []
}

我的目標是從對象中獲取數據,例如緯度和經度。 我嘗試了以下代碼:

$.ajax({
        type: "GET",
        url: 'URL TO MY JSON',
        dataType: "json",
        success: function (data) {
            if (data.length !== 0) {
                //Here I tried using data.markers istead of data, but it did not seem to work
                $.each( data, function (marker, data) {
                      //Here I want to be able to access e.g. data.longitude
                });
            }

        },

    });

問題似乎是它沒有正確導入數據。

我該如何解決?

謝謝

確保您正在遍歷數組的markers屬性。 因此,請調整if條件以及要迭代的對象:

success: function (data) {
    if (data.markers.length !== 0) {
        $.each(data.markers, function (index, marker) {
            alert(marker.longitude);
        });
    }
}

還要注意,傳遞給$.each函數的回調的第一個參數是數組中元素的索引,第二個參數是元素本身。 或者,您可以使用this來訪問要迭代的當前元素:

$.each(data.markers, function () {
    alert(this.longitude);
});

暫無
暫無

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

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