Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON in javascript using jQuery

I'm pulling my hair out over this. I am using jQuery.getJSON() method to get a response from a server. This is an example reponse:

{
  "playlist": {
      "track": {
          "song": "Wake me up",
          "albumart": "http://example.com/image.png",
          "videoid": "CDsKBof4iMA"
      }
  }
}

There will be more than one track in the response, but only one playlist. I am requesting this using the following:

$.getJSON("api/playlist/get.php", {artist: "artist+name" })

How do I go about parsing this data?

like image 372
James Walker Avatar asked Mar 21 '26 10:03

James Walker


1 Answers

Let's say your JSON result is like this:

{

    "playlist": {
        "track": {
            "song": "Wake me up",
            "albumart": "http://example.com/image.png",
            "videoid": "CDsKBof4iMA"
        },
        "track": {
            "song": "Wake me up 2",
            "albumart": "http://example.com/image2.png",
            "videoid": "CDsKBof4iMA2"
        },
        "track": {
            "song": "Wake me up 3",
            "albumart": "http://example.com/image3.png",
            "videoid": "CDsKBof4iMA3"
        }
    }
}

UPDATE:

This json is invalid format, because it has multiple sub-objects with same property name. If you are able, change response from server into this format:

{
    playlist: {
        tracks: [{
            "song": "Wake me up",
            "albumart": "http://example.com/image.png",
            "videoid": "CDsKBof4iMA"
        }, {
            "song": "Wake me up 2",
            "albumart": "http://example.com/image2.png",
            "videoid": "CDsKBof4iMA2"
        }, {
            "song": "Wake me up 3",
            "albumart": "http://example.com/image3.png",
            "videoid": "CDsKBof4iMA3"
        }]
    }
}

Then you'll be able to get each track object from passed Array:

You should use you $.getJSON function like this:

$.getJSON("api/playlist/get.php", function (data) {

    for (var key in myObj.playlist.tracks) {
        //do something with your track object
        console.log(myObj.playlist.tracks[key].song)
    }

})

Here is JsFiddle for you: http://jsfiddle.net/zur4ik/Fy6ud/1/

like image 154
zur4ik Avatar answered Mar 24 '26 00:03

zur4ik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!