[英]How to get the key and pair value from json if the pair value as string
下面是我的json響應
{
"head": null,
"body": {
"8431073": "CN0028-00"
},
"responseTime": null,
"leftPanel": null
}
我喜歡從身體中獲得關鍵和價值。 以下是我想使用ajax調用的鍵和值。 但返回的空值。
$.ajax({
url: "ulhcircuit.json",
method: "GET",
contentType: "application/json; charset=utf-8",
success: function(data) {
result = data.body;
gethtmlvalues(result);
$("#dialog_loading").hide();
},
fail: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
$("#dialog_loading").hide();
}
});
function gethtmlvalues(result) {
var circuitList = result;
var cktInstId = "";
var cktName = "";
if (circuitList != null) {
if (circuitList.length > 0) {
$.each(circuitList, function(key, value) {
cktInstId = key; // returns empty values
cktName = value; // returns empty values
});
}
}
}
我想將cktInstId作為8431073和cktName作為CN0028-00
請幫助我。謝謝
當您的響應輸入gethtmlvalues
,您將傳遞data.body
,它基於您提供的JSON如下所示:
{ "8431073": "CN0028-00" }
這是一個普通的JS對象,而不是列表,並且length
屬性的存在並不意味着它包含的項目數量。 這意味着您不需要長度檢查(正在比較undefined > 0
)。 您也不需要(錯誤地)命名為多余的變量circuitList
,只需使用result
。
function gethtmlvalues(result){
if(result != null){
$.each(result,function(key, value){
console.log(key, value); // this will print your key value pair
});
}
}
circuitList.length不是屬性,請使用Object.keys(circuitList).length。
var data = {"head": null,"body": {"8431073": "CN0028-00"},"responseTime": null,"leftPanel": null} var result = data.body; gethtmlvalues(result); function gethtmlvalues(result){ debugger; var circuitList = result; var cktInstId = ""; var cktName = ""; if(circuitList != null){ //if(circuitList.length > 0){ $.each(circuitList,function(key, value){ console.log(key); console.log(value); cktInstId = key; // returns empty values cktName = value; // returns empty values }); //} } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.