javascript - 循环嵌套 json 对象并显示键/值对

标签 javascript jquery json

我有一个 json 对象,我想打印它的键/值对组合。但我的对象是嵌套的。所以我想循环遍历每个对象并显示其键/值对。

fiddle :http://jsfiddle.net/ydzsaot5/

代码:

var html='';
var contextObj = {"CategoryID":"1","BillerID":"23","BillerName":"MERCS","RequestType":"QuickPay","AccountNo":"1234567890","Authenticator":"{\"EmailAddress\":\"dfgsdfgsdfg\",\"MobileNumber\":\"65-4576573\",\"ID\":\"4572-4756876-8\"}","Token":"3C639AE65"};

html = getKeyValueJson(contextObj, html);
$('div').html(html);
function getKeyValueJson(obj, html) {
    $.each(obj, function (key, value) {
        if (value == null) {
            return
        }
        if (typeof value == 'object') {
            getKeyValueJson(value, html);
        }
        else {
            html += '<label>' + key + '</label> :-  <label>' + value + '</label><br>';
        }
    });
    return html;
}

我想以这种方式打印:

....
AccountNo :- 1234567890
EmailAddress :- dfgsdfgsdfg
MobileNumber :- 65-4576573
....
Token :- 3C639AE65

最佳答案

问题出在你的 json 和你的代码中,你只是将它作为字符串给出

"{\"EmailAddress\":\"dfgsdfgsdfg\",\"MobileNumber\":\"65-4576573\",\"ID\":\"4572-4756876-8\"}" 

更改为

{"EmailAddress":"dfgsdfgsdfg","MobileNumber":"65-4576573","ID":"4572-4756876-8"}

var html = '';
var contextObj = {
  "CategoryID": "1",
  "BillerID": "23",
  "BillerName": "MERCS",
  "RequestType": "QuickPay",
  "AccountNo": "1234567890",
  "Authenticator": "{\"EmailAddress\":\"dfgsdfgsdfg\",\"MobileNumber\":\"65-4576573\",\"ID\":\"4572-4756876-8\"}",
  "Token": "3C639AE65"
};

html = getKeyValueJson(contextObj, html);
$('div').html(html);

function getKeyValueJson(obj, html) {
  $.each(obj, function(key, value) {
    
    value = parseIt(value) || value;
    
    if (value == null) {
      return
    }
    console.log(typeof value);
    if (typeof value == 'object') {
      html += getKeyValueJson(value, html);
    } else {
      html += '<label>' + key + '</label> :-  <label>' + value + '</label><br>';
    }
  });
  return html;
}

function parseIt(str) {
  try { return JSON.parse(str);  } catch(e) { return false; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
</div>

关于javascript - 循环嵌套 json 对象并显示键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26271169/

相关文章:

javascript - HTML canvas art,从草图生成坐标数据

javascript - 为什么需要 useRef 而不是可变变量?

jquery - 使用 JQuery 获取对 PrimeFaces widgetVar 的引用

c# - 为下拉列表设置标题

javascript -/(\S)\1(\1)+/g 匹配三个相等的非空白字符的所有出现

javascript - 使用 Date.parse 对有效日期的确定不一致

javascript - 禁用光标/编辑但保持聚焦能力

json - 使用Moshi解析JSON中的包装对象

css - base url em slded css data-lazyload

php - 从 MYSQL 中获取数据并显示在 JSON 文件中