Reputation: 604
I need to search through JSON data and find every object that contains the "kind" "playlist" and then go through the tracks and pull information which will be put into a hmtl list. The problem is that in some instances (depending on the type of URL) instead of a multidimensional array containing all the objects, the json information is just a singular object.
Below are the two url types.
This is a playlist which contains just one level of information. http://api.soundcloud.com/playlists/1980151.json?client_id=bcc776e7aa65dbc29c40ff21a1a94ecd
This is an array which contains just multiple playlists as objects. http://api.soundcloud.com/users/dubstep/playlists.json?client_id=bcc776e7aa65dbc29c40ff21a1a94ecd
The current code I have is this:
$.getJSON('http://api.soundcloud.com/users/dubstep/playlists.json?client_id=bcc776e7aa65dbc29c40ff21a1a94ecd', { get_param: 'value' }, function(url_data) {
$.each(url_data, function (i, elem) {
if (elem.kind === 'playlist') {
$.each(elem.tracks, function (i, elem) {
console.log(elem.title);
});
}
});
});
It only works when dealing with "user" urls where there are multiple playlists.
To sum up what my issue is, I need a way to search through all the levels of an array to find levels with the kind === playlist.
Upvotes: 3
Views: 14266
Reputation: 25081
This should do what you're looking for.
$.each(json, function (i, elem) {
if (elem.kind === 'playlist') {
$.each(elem.tracks, function (i, elem) {
console.log(elem.title);
});
}
});
UPDATE:
This will work with either URL. Also, here's a fiddle with more a more advanced client-side output: http://jsfiddle.net/jTLvE/
var parse = function (json) {
$.each(json, function (i, elem) {
if (elem.kind === 'playlist') {
$.each(elem.tracks, function (i, elem) {
console.log(elem.title);
});
}
});
},
parseReturnedData = function (json) {
var isObject = (typeof json === 'object' && json instanceof Object),
isArray = (typeof json === 'object' && json instanceof Array),
newArray = [];
if (isArray) {
parse(json);
} else if (isObject) {
newArray.push(json);
parse(newArray);
}
};
Upvotes: 12
Reputation: 761
try this code:
var objJson = jQuery.parseJSON(json);
jQuery.each(objJson , function(i, val) {
alert(val);
});
Upvotes: -1
Reputation:
Have you tried json path? I used it and it's small and fast, especially for searching json trees (for searching and writing I'd use flock though).
Upvotes: 0