You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Smarty解析YouTube API返回的JSON文件并排查代码问题

问题原因

  • 遍历对象错误:你直接遍历了JSON解析后的根响应对象,实际视频数据存放在根对象下的items数组中,需要遍历该数组
  • 取值路径错误:snippet是items数组内单个视频对象的子属性,不是直接挂载在items集合下的属性

正确实现代码

对象写法(默认情况)

{capture assign=feed}{cache_remote_file url="https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id=Duf5UUT......"}{/capture}

{$videoList = $feed|json_decode}
{foreach from=$videoList->items item=video}
<p> title : {$video->snippet->title}  </p>
<p> img : {$video->snippet->thumbnails->default->url}  </p>
{/foreach}

关联数组写法(兼容所有Smarty版本)

如果上述代码运行报错,可使用关联数组写法,json_decode传入第二个参数true即可返回关联数组:

{capture assign=feed}{cache_remote_file url="https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id=Duf5UUT......"}{/capture}

{$videoList = $feed|json_decode:true}
{foreach from=$videoList['items'] item=video}
<p> title : {$video['snippet']['title']}  </p>
<p> img : {$video['snippet']['thumbnails']['default']['url']}  </p>
{/foreach}

内容的提问来源于stack exchange,提问作者Andrew Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:27:03