簡體   English   中英

遍歷嵌套的json對象並顯示kay / value對

[英]loop through nested json objects and display kay/value pair

我有想要打印其key/value對組合的json對象。 但是我的對象是嵌套的。 所以我想遍歷每個對象並顯示其鍵/值對。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM