Jquery parse json

I cannot parse the JSON, which I have no control over. 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]);
      });
    });

      

+2


a source to share


1 answer


JSON is poorly 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]
 }]
}

      

This is why you are having trouble parsing.

If you have no control over it, but you know it will be in a similar form, you can use jQuery.ajax

and then convert it to valid JSON with some string manipulation or whatever. This is probably not ideal, but it is the only thing you can do if you have no control over the JSON returned.

Also note that you have two keys with the same name. This is another problem.

To fix this, 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]
 }]
}

      

As I mentioned earlier, given that you are not in control of JSON, there is little you can do about it. I would recommend talking to the admin / developer of this site if you can, though. They need to be advised that they are not returning valid JSON.

+9


a source







All Articles