简体   繁体   中英

Json iteration Javascript

I have a json string {"email" : "Hello", "username" : "Not taken"}

how do I iterate through this json to display the text (Like Hello)

I want to display the following text

Email : Hello
Username : Not taken

I tried the following:

    arr = json
    $.each(arr, function(k, v) {
      message += k + ':' + v + '<br />';  
    });

You need to change the JSON string to a Javascript object. Use JSON.parse() .

Demo: jsFiddle

Output:

输出

Script:

var json = '{"email" : "Hello", "username" : "Not taken"}',
    arr = window.JSON.parse( json ),
    message = '';

$.each(arr, function(k, v) {
    message += k + ': ' + v + '<br />';  
});

document.getElementById( 'message' ).innerHTML = message;

HTML:

<div id="message"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM