簡體   English   中英

使用jQuery從JSON獲取值

[英]Getting Values from JSON with jQuery

我得到以下字符串:

[{"Key":1,"Value":"correct"},{"Key":2,"Value":"incorrect"},{"Key":3,"Value":"incorrect"},{"Key":4,"Value":"correct"},{"Key":5,"Value":"incorrect"}]

我想根據該TR的ID在JSON中具有“正確”還是“不正確”的值來更改TR的背景顏色。

如何從JSON獲取單個項目的值? 我努力了:

            success: function (result) {
                // update with results
                //alert(JSON.stringify(result));
                //$('#myDiv').html(JSON.stringify(result));

                // non of these work
                alert(result[0]);
                alert(result[key]);
            },

您可以使用$.each()迭代對象數組。

$.each(result, function(i, item) {
    alert(item.Key);
});

$.each()的回調中, item將是對要迭代的Array中當前項目的引用。

然后,您只需使用常規屬性訪問即可獲取Key屬性的值。


當然,您也可以使用傳統的for語句來循環數組。

for (var i = 0; i < result.length; i++) {
    var item = result[i];
    alert(item.Key);
}

所有這些都假定您的響應具有正確的Content-Type設置,或者已將dataType:"json"賦予$.ajax()

您可以將JSON格式轉換為Object,在您的情況下它將是array,因此您可以使用forEach來檢查所需內容。

嘗試這個

var obj= JSON.parse( '[{"Key":1,"Value":"correct"},{"Key":2,"Value":"incorrect"},{"Key":3,"Value":"incorrect"},{"Key":4,"Value":"correct"},{"Key":5,"Value":"incorrect"}]' );



obj.forEach(function(i){alert(i.Key);alert(i.Value) })

看一下這個: http : //goessner.net/articles/JsonPath/。我沒有使用它,但是看起來是從Json結構中獲取值的好方法。

確保在Ajax請求中指定.. dataType:'json'

嘗試

alert(result[0]["key"]);  // For the first

//

$.each(result , function(i) {
    console.log( 'Key is - ' + result[i]["Key"] + ' -- Value is - ' + result[i]["Value"]);
});

檢查FIDDLE

您沒有指定,但是假設JSON字符串是您的Ajax代碼作為響應接收的內容,那么您實際上是對該文本重新進行JSON轉換,因此它變成了雙重編碼的字符串。

如果您知道期望json作為響應,則jQuery可以自動將其解碼回本機結構,例如

$.ajax({
   dataType: 'json',
   etc...
});

那你就只有

alert(result[0]['key']);

要么

data = jquery.parseJSON(result);
alert(data[0]['key']);

暫無
暫無

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

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