循环遍历嵌套的json对象并显示键/值对

时间:2014-10-09 05:48:29

标签: javascript jquery json

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

小提琴: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

1 个答案:

答案 0 :(得分:2)

问题出在您的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>