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

标签 javascript jquery json

下面是我的 json 响应

{
  "head": null,
  "body": {
    "8431073": "CN0028-00"
  },
  "responseTime": null,
  "leftPanel": null
}

我喜欢从 body 中获取键和值。下面是我的 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
      });
  }
}

关于javascript - 如果对值是字符串,如何从 json 获取键和对值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39772317/

相关文章:

javascript - 行数据未定义

javascript - 如何确定要提交的 HTTP POST 事务的大小?

javascript - 将 'active' 类添加到幻灯片导航

javascript - 右键单击“检查元素”(selenium)后出现错误行

javascript - jquery 微醉插件

php - 如何在 AngularJS 和 PHP 中获取最大数量的 JSON 记录作为响应

php - Steam 网络 API : How to get the tags for items in Steam Inventory

ios - 在 iOS 内容拦截器中使用多个 JSON 列表

javascript - CoffeeScript:对象初始化器中的 Getter/Setter

jQuery 淡出留下小间隙