user2219097
user2219097

Reputation: 357

JavaScript JSON Object Object error

I am trying to print out the key and value names from the data below e.g. "Player 1' - 'ball' 'hat' and "Player 2 - 'ball, 'hat'. So keys have multiple value names but im not sure how i print these out.** I am getting '[object Object]' as a response**. Can someone help me with this understanding please and trying to resolve the matter.

Data

{
    "Player1": {
        "ball": 1,
        "hat": 2

    },
    "Player2": {
        "ball": 1,
        "hat": 2,
    }
}

JavaScript

$.getJSON('data.json', function (data) {
    var response = data;
    for (key in response){
        alert("key: " + key + "value :" + response[key]);
    }
});

Upvotes: 0

Views: 25232

Answers (5)

arnav
arnav

Reputation: 61

The stringify function of JSON comes to rescue here. Since most internal functions take data parameters as string or sometimes buffer. Thus you can use the following code:-

    var response = {
    "Player1": {
        "ball": 1,
        "hat": 2

    },
    "Player2": {
        "ball": 1,
        "hat": 2,
    }
}

var dataString = JSON.stringify(response);

Now use dataString for sending and receiving over different calls.

Upvotes: 1

jyrkim
jyrkim

Reputation: 2869

Here's one way of printing the content of the object. Object.keys() method is used to access player's "items" and get those in array format. Updated.

var response = {
    "Player1": {
        "ball": 1,
            "hat": 2

    },
        "Player2": {
        "ball": 1,
            "hat": 2,
    }
};
for (player in response) {

    var items = Object.keys(response[player]);

    var itemText = "";
    for (i = 0; i < items.length; i++) {
        itemText += " '" + items[i] +  "'";
    }

    console.log(player +  " -" + itemText);
    
    //alternative way, suggested by NickCraver
    console.log(player +  " - "+ Object.keys(response[player]).map(function(k) { return '\''+k+'\''; }).join(' ') );
}

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630399

The simplest way to do this in any modern browser would be to use Object.keys() and just join the result into a string, like this:

for (key in response){
    alert("key: " + key + " value :" + Object.keys(response[key]).join(' '));
}

Result:

key: Player1 value :ball hat
key: Player2 value :ball hat

You can test it out here.

Upvotes: 6

void
void

Reputation: 36703

$.getJSON('data.json', function (data) {
    var response = data;
    for (key in response){
        alert("key: " + key + "value :" + JSON.stringify(response[key]));
    }
});

or use response[key].ball, response[key].hat

Upvotes: 1

Jimmy Bernljung
Jimmy Bernljung

Reputation: 529

Use JSON.stringify(response[key]) when printing the object.

Upvotes: 4

Related Questions