3

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"}"]

4 Answers 4

7

You can just use stringify method of JSON-

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

Sign up to request clarification or add additional context in comments.

Comments

2

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 );
        });
    });
}

Comments

1

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/

5 Comments

This give me: key 0 is {, key 1 is ", key 2 is i and so on
Is there some way to sort them out as key = id & value = 1, key = username & value = ghost and so on ?
What about json[0].id? Try it out with alert. It should work.
Then what you put in your question doesn't match the real scenario.
Hmm, the fiddle is working. But my code isn't. So the problem seems to be at this line then: var json = $.parseJSON(data);
1

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);
            });
    }
    });
}

6 Comments

This is the error message I'm getting: Uncaught TypeError: Cannot use 'in' operator to search for '114' in {"id":"1","username":"ghost","points":"5","kills":"18","xp":"10","diamonds":"0","level":"1","missionscomplete":"1"}
@AshishAgarwal: Please see my updated code. If you still see errors, please share the entire json array that is delivered by the API.
Also, what's the use of var json = $.parseJSON(data); ?
Updated the question with values of data and $.parseJSON(data)
After pasting the above code, I have the error: Uncaught TypeError: Cannot use 'in' operator to search for '114' in {"id":"1","username":"ghost","points":"5","kills":"18","xp":"10","diamonds":"0","level":"1","missionscomplete":"1"}
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.