tags:

views:

206

answers:

1
+2  Q: 

jquery parse json

I can't parse the JSON that I have no control of. What am I doing wrong here?

data.json

{
  "img": "img1.jpg",
  "img": "img2.jpg",
  "size": [52, 97]
}

{

  "img": "img3.jpg",
  "img": "img4.jpg",
  "size": [52, 97]
}

jquery

$.getJSON("data.json",
    function(data){
      $.each(data, function(i,item){
        alert(item.img[i]);
      });
    });
+7  A: 

The JSON is badly formed. It should be something like this:

{images: [{
  "img": "img1.jpg",
  "img": "img2.jpg",
  "size": [52, 97]
 },
 {

  "img": "img3.jpg",
  "img": "img4.jpg",
  "size": [52, 97]
 }]
}

That's why you're having trouble parsing it.

If you don't have control over it, but you know that it's going to be in a similar form, you can use jQuery.ajax and then convert it over to valid JSON through some string manipulation or something. Probably not ideal, but it's the only thing you can do given that you have no control over the JSON being returned.

Also note that you have two keys with the same name. That's another problem.

To fix that, you probably want something like the following:

{images: [{
  "img1": "img1.jpg",
  "img2": "img2.jpg",
  "size": [52, 97]
 },
 {

  "img3": "img3.jpg",
  "img4": "img4.jpg",
  "size": [52, 97]
 }]
}

or

{images: [{
  "img": ["img1.jpg", "img2.jpg"],
  "size": [52, 97]
 },
 {

  "img": ["img3.jpg", "img4.jpg"],
  "size": [52, 97]
 }]
}

I think an even better way would be something like this:

{images: [{
   img: "img1.jpg",
   size: [52, 97]
 },
 {   
   img: "img2.jpg", 
   size: [52, 97]
 },
 {   
   img: "img3.jpg", 
   size: [52, 97]
 },
 {   
   img: "img4.jpg", 
   size: [52, 97]
 }]
}

Like I mentioned before, given that you have no control over the JSON there is little you can do. I would recommend talking to the admin/developer of that site if you can, though. They do need to be informed that they are not returning valid JSON.

Vivin Paliath