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?
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"
}
}
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With