简体   繁体   中英

jquery get json with nested arrays

I am working with a music player that need to get json value from a page dynamically the first thing i am struggling is the json is some thing like this

{"audios":[{"audio":{"name":"makakyala","audio":{"audio":{"url":"/uploads/audio    /audio/9/01_-_Makkayala_SouthSongs4u.com_.mp3"}}}},{"audio":{"name":"tahppellam","audio":{"audio":{"url":"/uploads/audio/audio/10/03_-_Thapellam_Thape_Illai_SouthSongs4u.com_.mp3"}}}},{"audio":{"name":"dinam dinam","audio":{"audio":{"url":"/uploads/audio/audio/11/04_-_Dinnam_Dinnam_SouthSongs4u.com_.mp3"}}}}]}

I need each audio array to be passed to jquery and my jquery code is

$.getJSON("../albums/x.json",function(json){  
    $.each(json.audios,function(index, audio){
       $.each(audio, function(audio) {
        as=JSON.stringify(audio)
        alert(as)
        myPlaylist.add({title:$(this).attr("audio_name")}); 
     })
        })
     });

but its not working what is the problem with my code and how can i get each audio array form audios array ?

change this :

$.each(audio, function(audio) {

to this:

$.each(audio, function(idx, audio) {

In your second $.each() iteration you need to put it as a second argument because first arg or if single arg passed in the callback gives you the key of the js object not the object itself. So you need to put this in second argument as suggested above.


Demo


This will get you the url you are looking for:

$.each(audio, function(idx, audio) {
    console.log(audio.audio.audio.url);
});

Demo to get the each url

There is nothing wrong in your code. Check what header you passing when sending the response. You should set response header as header('Content-Type: application/json');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM