Reputation: 795
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?
Upvotes: 3
Views: 109
Reputation: 6254
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/
Upvotes: 1
Reputation: 10996
As per the documentation,
jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )
In this, the success( data, textStatus, jqXHR )
is the callback if the JSON load was successful
Upvotes: 0
Reputation: 5879
Use $.parseJSON()
to get a JavaScript object of the JSON.
http://api.jquery.com/jQuery.parseJSON/
Upvotes: 0
Reputation: 1355
Try this:
$.getJSON("api/playlist/get.php", function(data) {
var responseObject = JSON.parse(data);
// do stuff with responseObject
});
Upvotes: 0