-1

I'm getting this output:

0 [object Object] 
1 [object Object] 
2 [object Object] 
3 [object Object] 

jQuery:

$.getJSON(url, {
    sessionId: "1"
}).done(function(data) {
    alert("Successfully got the messages! ");

    $target.empty();

    var messages = [];

    $.each(data,function(k,v) {

        console.log(k + " " + v);

    });


    $target.append(data);
}).fail(function() {
    alert("Could not reload messages!");
});

The response:

[
  {
    "date": "2014-02-19",
    "user_viewer": null,
    "message": "Hey mate, can you do 20:00?",
    "user_op": "john",
    "time": "18:21:00"
  },
  {
    "date": "2014-02-20",
    "user_viewer": null,
    "message": "@simon, you can borrow one from the desk, it's 1 pound.",
    "user_op": "roger",
    "time": "00:00:00"
  }
]
chuckfinley
  • 2,577
  • 10
  • 32
  • 42

1 Answers1

1

Use:

$.getJSON(url, {
    sessionId: "1"
}).done(function(data) {
    alert("Successfully got the messages! ");

    $target.empty();

    var messages = [];

    $.each(data,function(k,v) {
        console.log(k + " " + JSON.stringify(v));
    });


    $target.append(data);
}).fail(function() {
    alert("Could not reload messages!");
});
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
  • Maybe you can explain a bit more what the problem is and how `JSON.stringify` solves it? – Felix Kling Mar 17 '14 at 21:04
  • v is now returning this: {"date":"2014-02-19","user_viewer":null,"message":"Hey mate, can you do 20:00?","user_op":"john","time":"18:21:00"}. However, when i try to read it using var item = JSON.stringify(v); console.log(item.message); it does not work. any idea why? – chuckfinley Mar 17 '14 at 21:06
  • 1
    @chuckfinley `JSON.stringify(v)` will return you the string representation of the object. You cannot access the key `message` of a string. – Whymarrh Mar 17 '14 at 21:07
  • 1
    Yes. Use `var item = v;`. `JSON.stringify` returns the strigified version, so it is a string. – Minko Gechev Mar 17 '14 at 21:07
  • @MinkoGechev so this doesn't help me. How do i access the elements? – chuckfinley Mar 17 '14 at 21:08
  • Use `var item = v; console.log(item.message);`. This way you access the elements. `JSON.stringify` helps only to print them in a useful form. – Minko Gechev Mar 17 '14 at 21:09