最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Printing JSON Dictionary in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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","missionsplete":"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\",\"missionsplete\":\"1\"}","{\"id\":\"2\",\"username\":\"seconduser\",\"points\":\"0\",\"kills\":\"3\",\"xp\":\"0\",\"diamonds\":\"0\",\"level\":\"0\",\"missionsplete\":\"0\"}","{\"id\":\"3\",\"username\":\"goat\",\"points\":\"12\",\"kills\":\"13\",\"xp\":\"14\",\"diamonds\":\"10\",\"level\":\"10\",\"missionsplete\":\"4\"}"] 

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

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

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","missionsplete":"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\",\"missionsplete\":\"1\"}","{\"id\":\"2\",\"username\":\"seconduser\",\"points\":\"0\",\"kills\":\"3\",\"xp\":\"0\",\"diamonds\":\"0\",\"level\":\"0\",\"missionsplete\":\"0\"}","{\"id\":\"3\",\"username\":\"goat\",\"points\":\"12\",\"kills\":\"13\",\"xp\":\"14\",\"diamonds\":\"10\",\"level\":\"10\",\"missionsplete\":\"4\"}"] 

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

["{"id":"1","username":"ghost","points":"5","kills":…diamonds":"0","level":"1","missionsplete":"1"}", "{"id":"2","username":"seconduser","points":"0","ki…diamonds":"0","level":"0","missionsplete":"0"}", "{"id":"3","username":"goat","points":"12","kills":…amonds":"10","level":"10","missionsplete":"4"}"]
Share Improve this question edited Sep 21, 2013 at 5:44 Ashish Agarwal asked Sep 21, 2013 at 3:22 Ashish AgarwalAshish Agarwal 14.9k31 gold badges88 silver badges126 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

You can just use stringify method of JSON-

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

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[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/UTyDa/

jQuery.each() is probably the easiest way, check this out: http://api.jquery./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);
            });
    }
    });
}
发布评论

评论列表(0)

  1. 暂无评论