循环遍历嵌套的json对象并显示kay/value对

loop through nested json objects and display kay/value pair

本文关键字:kay 显示 value 对象 遍历 嵌套 json 循环      更新时间:2023-09-26

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

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>