繁体   English   中英

无法从json数组动态获取数据

[英]Not able to fetch data from json array dynamically

我有json数组

JSON.stringify(ar)

当我用来分散警报中的结果时

alert(JSON.stringify(ar));

它会按原样显示。 警报中的输出很简单

[{“ url”:“ link1”,“ title”:“ title1”}]

但是当我用来将其内容传输到播放列表数组中时,就像

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

并尝试显示其结果,这给了我错误,给了我未定义的

请帮我整理一下。

在这之后

var playlist=[];

playlist=JSON.stringify(ar)

播放列表包含字符串,因此,如果要提取url,则需要再次解析该JSON

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

但是,如果您输入[1]则该数组需要具有两个元素:

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

您需要处理对象本身。 当您输出对象或通过电线发送它们时,仅需要JSON.stringify以可读格式显示它们。

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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