0

Json data with this structure:

Title_day_hourminsec([
{"data":"x", "type":"y"},
{"data":"x", "type":"y"},
{"data":"x", "type":"y"},
{"data":"x", "type":"y"},
{"data":"x", "type":"y"},
{"data":"x", "type":"y"},
]);

from the call of jquery getJSON I'm not able to get the real content of the file, only got this is the html output:

[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]

this is the javascript snippet I've tried to get the json content:

<script type="text/javascript">

 $(document).ready(function(){
    $.getJSON("myremotedata",
      function(data){
      var items = [];

 $.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
 $('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
        });
  });


</script>

What am I missing?

user2239318
  • 2,578
  • 7
  • 28
  • 50
  • 1
    The data shown is not valid JSON. Is it supposed to be JSONP? – nnnnnn Sep 04 '13 at 13:36
  • 2
    You get an array of objects. `[object Object]` is the **default string representation** of an object. If you want to display specific properties, then you have to [access them](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators). – Felix Kling Sep 04 '13 at 13:37
  • $.getJSON will parse the response automatically using JSON.parse() and that's why you end up with the JavaScript object. You can use $.get() instead if you need the response to be in JSON format unparsed. – Ahmed Mansour Apr 21 '17 at 14:29

2 Answers2

6

Try to modify your each loop like:

$.each(data, function (key, val) {
    items.push('<li id="' + key + '">' + val.data + ' ' + val.type + '</li>');
});

You are getting [object Object] since in the each loop, the variable val is actually an object. You need to use the Javascript dot object notation like val.data or val.type to get the values of the each object.

palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

$.each() returns an index and the value at that index.

$.each(data, function(index, value) {
    // value contains {"data":"x", "type":"y"}
});

you can then use value.data or value.type for populating your list.

Robert
  • 386
  • 1
  • 8