如何提取JSON结构中多个同名url键对应的图片链接值
问题描述
我有如下JSON数据集:
{ "content":[], "layout":[], "trail":[ { "content":[ { "type":"image", "media":[ { "type":"image/jpg", "width":593, "height":900, "url":"https://live.staticflickr.com/65535/48208920877_e6b234d3ea_c_d.jpg", "flickr":{ "flickr-post":"https://www.flickr.com/photos/riketrs/48208920877", "flickr-album":"https://www.flickr.com/photos/riketrs/albums/72157709130951466" } } ] }, { "type":"image", "media":[ { "type":"image/jpg", "width":1600, "height":900, "url":"https://live.staticflickr.com/2817/33807326532_91013ef6b1_h_d.jpg", "flickr":{ "flickr-post":"https://www.flickr.com/photos/146758538@N03/33807326532", "flickr-album":"https://www.flickr.com/photos/146758538@N03/albums/72157681438471236" } } ] } ], "colors":{ "c0":"#1e1e1d", "c1":"#78736f", "c2":"#b2a89f" } } ] }
我希望通过console.log输出上述JSON中每张图片对应的"url"键值,即https://live.staticflickr.com/65535/48208920877_e6b234d3ea_c_d.jpg和https://live.staticflickr.com/2817/33807326532_91013ef6b1_h_d.jpg。
我对JSON整体还比较陌生,尝试编写了部分代码但未达到预期效果,也查阅了一些JSON相关的解答内容,还是不确定该如何实现需求。
解决方案
你需要先明确目标字段的层级路径:trail数组项 → content数组项 → media数组项 → url,按层级遍历数组就能拿到所有目标值,完整实现代码如下:
// 若你拿到的是JSON字符串,先转成JavaScript对象 const rawJson = `此处替换为你的JSON字符串`; const data = JSON.parse(rawJson); // 遍历层级取图片url data.trail.forEach(trailItem => { trailItem.content.forEach(contentItem => { // 过滤非图片类型内容,避免非预期报错 if (contentItem.type !== 'image') return; contentItem.media.forEach(mediaItem => { console.log(mediaItem.url); }) }) })
如果你的数据已经是解析完成的JS对象,跳过JSON.parse步骤直接执行遍历逻辑即可,运行后控制台会依次输出两张图片的url地址。
内容的提问来源于stack exchange,提问作者deadweig-ht
相关产品推荐
相关产品推荐

