繁体   English   中英

如果成对值是字符串,如何从json获取键和成对值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM