简体   繁体   中英

Not able to fetch data from json array dynamically

i have json array

JSON.stringify(ar)

when i use to dispaly the results in alert like

alert(JSON.stringify(ar));

it will show as they are. the output in the alert is simple this

[{"url":"link1","title":"title1"}]

but when i use to transfer its contents into an array of playlist, Like

var playlist=[];
playlist=JSON.stringify(ar); alert (JSON.stringify(playlist[1].url));

and try to show its results it is giving me the error and giving me undefined

Please help me to sort it out.

After this

var playlist=[];

playlist=JSON.stringify(ar)

playlist contain the string so if you want to extract url you need to parse that JSON again

alert(JSON.parse(playlist)[1].url);

but if you put [1] then the array need to have two elements:

[{"url":"link1","title":"title1"},{"url":"link1","title":"title1"}]

You need to deal with the objects themselves. JSON.stringify is only needed to display them in a readable format, when you are outputting the objects or sending them over the wire or so.

var ar = [{"url":"link1","title":"title1"}]

alert(ar); // equivalent to alert(ar.toString()), will show [object Object]
alert(JSON.stringify(ar)); // will show [{"url":"link1","title":"title1"}]
console.log(ar); // the proper way to do it, inspect the result in console

var playlist=[];

// then do either
playlist = playlist.concat(ar);
// or
playlist.push.apply(playlist, ar);
// or
playlist.push(ar[0]);
// or
playlist[0] = ar[0];
// or
playlist = ar;
// (which all do a little different things)
// but notice none of them used JSON.stringify!

// now you can
console.log(playlist)
alert(playlist[0].url); // shows link1 - this is what you want
alert(JSON.stringify(playlist[0].url)); // shows "link1"

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