[英]How to get the key and pair value from json if the pair value as string
Below is my json response 下面是我的json响应
{
"head": null,
"body": {
"8431073": "CN0028-00"
},
"responseTime": null,
"leftPanel": null
}
I like to get the key and value from body. 我喜欢从身体中获得关键和价值。 Below is my ajax call where i would like to take the key and value.
以下是我想使用ajax调用的键和值。 but its returning empty value.
但返回的空值。
$.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
});
}
}
}
I would like to have the cktInstId as 8431073 and cktName as CN0028-00 我想将cktInstId作为8431073和cktName作为CN0028-00
Please help me.Thanks in advance 请帮助我。谢谢
When your response enters gethtmlvalues
, you are passing data.body
, which based on the JSON you've given looks like: 当您的响应输入
gethtmlvalues
,您将传递data.body
,它基于您提供的JSON如下所示:
{ "8431073": "CN0028-00" }
This is a plain JS object, not a list, and existence of a length
property doesn't mean amount of items it contains. 这是一个普通的JS对象,而不是列表,并且
length
属性的存在并不意味着它包含的项目数量。 This means you don't need the length check (you are comparing undefined > 0
). 这意味着您不需要长度检查(正在比较
undefined > 0
)。 You also don't need a (wrongly) named extra variable circuitList
, you can just use result
. 您也不需要(错误地)命名为多余的变量
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 is not a property, use Object.keys(circuitList).length. 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.