简体   繁体   中英

Printing JSON Dictionary in JavaScript

I am getting the data from an API using JavaScript.

The statement console.log(json[0]) gives the result:

{"id":"1","username":"ghost","points":"5","kills":"18","xp":"10","diamonds":"0","level":"1","missionscomplete":"1"} 

Now I am trying to print the individual elements of this dictionary. How do I do this ? My code is below:

function loadLeaderboard(){
    $.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
        var json = $.parseJSON(data);
        console.log(json[0]);
        $.each(json[i], function(key, data) {
            console.log(key + ' -> ' + data);
        });
    });
}

EDIT : The value of data as returned by the API is

["{\"id\":\"1\",\"username\":\"ghost\",\"points\":\"5\",\"kills\":\"18\",\"xp\":\"10\",\"diamonds\":\"0\",\"level\":\"1\",\"missionscomplete\":\"1\"}","{\"id\":\"2\",\"username\":\"seconduser\",\"points\":\"0\",\"kills\":\"3\",\"xp\":\"0\",\"diamonds\":\"0\",\"level\":\"0\",\"missionscomplete\":\"0\"}","{\"id\":\"3\",\"username\":\"goat\",\"points\":\"12\",\"kills\":\"13\",\"xp\":\"14\",\"diamonds\":\"10\",\"level\":\"10\",\"missionscomplete\":\"4\"}"] 

The value in json after the operation var json = $.parseJSON(data); is

["{"id":"1","username":"ghost","points":"5","kills":…diamonds":"0","level":"1","missionscomplete":"1"}", "{"id":"2","username":"seconduser","points":"0","ki…diamonds":"0","level":"0","missionscomplete":"0"}", "{"id":"3","username":"goat","points":"12","kills":…amonds":"10","level":"10","missionscomplete":"4"}"]

json[0] is an object, so you want to loop over the keys:

var o = json[0];
for (var key in o) {
    if (o.hasOwnProperty(key)) {
        console.log(key, o[key]);
    }
}

Working fiddle: http://jsfiddle.net/UTyDa/

Update

Your JSON data is a mess. It's not in the format you want. It should be an array of objects, but instead it is an array of strings , where each of those strings is the JSON representation of one of your user objects.

You could decode this in your JavaScript code, but you shouldn't have to. The JSON API should be fixed to generate a reasonable JSON object.

I don't know what language your server code is in, but it must be doing something like this pseudocode:

array = []
for each userObject in leaderBoard:
    userJson = toJSON( userObject )
    array.push( userJson )
jsonOutput = toJSON( array )

Instead, the code should look more like this:

array = []
for each userObject in leaderBoard:
    array.push( userObject )
jsonOutput = toJSON( array )

In other words, the way to generate the JSON you want in most languages is to create an object or array with the structure you need, and then call the language's toJSON function (or whatever function you use) on that object or array. Let it generate all of the JSON in one fell swoop. Don't generate JSON for each individual element of your array and then generate JSON again for the entire array as a whole. That gives you an array of strings where you want an array of objects.

Original answer

What you're asking for is not what you really want to do.

Your JSON response returns an array of user objects, correct? That's why json[0] is a single object.

You probably want to loop over that array , but you don't loop over the individual objects in the array. You simply reference their properties by name.

Also, instead of using $.get() and $.parseJSON() , you can use $.getJSON() which parses it for you.

And one other tip: don't put the hostname and port in your URL. Use a relative URL instead, and then you can use the same URL in both development and production.

So for test purposes, let's say you want to log the id , username , and points for each user in your leaderboard JSON array. You could do it like this:

function loadLeaderboard() {
    var url = '/l4/public/api/v1/getLeaderboard';
    $.getJSON( url, function( leaders ) {
        // leaders is an array of user objects, so loop over it
        $.each( leaders, function( i, user ) {
            // get the properties directly for the current user
            console.log( user.id, user.username, user.points );
        });
    });
}

您可以只使用JSON-的stringify方法

console.log(JSON.stringify(json[0]));

jQuery.each() is probably the easiest way, check this out: http://api.jquery.com/jQuery.each/

eg

$.each(json[0], function(key, data) {
    console.log(key + ' -> ' + data);
});

EDIT:

What's the result of the following?

function loadLeaderboard(){
    $.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
        var json = $.parseJSON(data);
        console.log(json[0]);
        for(var i = 0; i < json.length; i++) {
            $.each(json[i], function(key, data) {
                console.log(key + ' -> ' + data);
            });
        }
    });
}

EDIT 2: 'data' returned as array.

function loadLeaderboard(){
    $.get("http://localhost:8888/l4/public/api/v1/getLeaderboard", function(data){
    for(var i = 0; i < data.length; i++) {
            var json = $.parseJSON(data[i]);
            console.log('Data for index: ' + i);
            $.each(json, function(key, val) {
                    console.log(key + ' -> ' + val);
            });
    }
    });
}

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