Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery not parsing JSON properly

I have a problem. I built a script to make a request to an internal link that sends back a response. This is what the script looks like:

jQuery.get(callUrl, function(data) {
  console.log(typeof data);
  jQuery.each(data.items, function(i, item) {

    console.log(i);
  });
}, 'json');

and the response that the server sends back looks like this:

{"items":[            
  {
   "src": "gallery_item_data_Jc4EaLP6vlwd_large.jpg",
   "id": "83",
   "gallery_id": "30",
   "username": "admin"
  }]
}

My problem is when I parse the "data" its type is always string. I need for it to be an object so that I can query it and parse it with my script. To get to the bottom of the problem, I've tried comparing my script to the example on jQuery's documentation page:

http://docs.jquery.com/Ajax/jQuery.getJSON

The main differences with the request on this page and my request is that it uses the getJSON method. When I tried to use that with the url to my server, I have gotten no response at all, so that is the main reason I opted for the get method, and specifying the return type as "json."

Another thing I tried: I checked out the Flickr feed that the jQuery example uses to look for the Content-type header that it sends back, thinking maybe my feed had the wrong header, and it is this on the Flickr feed:

Content-Type    application/x-javascript; charset=utf-8

This is exactly the same header on my own feed. So I am puzzled. Does anyone know why this is happening?

like image 747
picardo Avatar asked Dec 17 '08 16:12

picardo


1 Answers

The JSON needs to have brackets around it, so it should be:

({"items":[            
  {
   "src": "gallery_item_data_Jc4EaLP6vlwd_large.jpg",
   "id": "83",
   "gallery_id": "30",
   "username": "admin"
  }]
})

You should then be able to use getJSON, as this is the easiest way to get the data as an object. However, you can also eval() the string and that will return an object.

like image 58
Mark Bell Avatar answered Sep 25 '22 17:09

Mark Bell