2014-10-09 290 views
0

我有json對象,我想要打印它的key/value對組合。但我的對象是嵌套的一個。所以我想遍歷每個對象並顯示它的鍵/值對。通過嵌套的json對象循環並顯示kay /值對

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

回答

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>

+0

你可以解決這個問題,而不改變'json'對象? – Shaggy 2014-10-09 06:00:44

+1

你可以使用像'JSON.parse()' – 2014-10-09 06:01:31

+0

這樣的東西,如果你在小提琴中展示它會很棒 – Shaggy 2014-10-09 06:04:01