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

JavaScript/Node.js 如何从JSON数组中获取指定元素的id字符串值

实现步骤

你只需要先把JSON字符串解析为JavaScript对象(如果已经是对象可跳过解析步骤),再按层级取值即可,示例代码如下:

// 1. 若你拿到的是JSON字符串,先执行解析
const jsonStr = `{
  "videos": [
    {
      "id": "jbnddQ9l0IA",
      "original_title": "Undefined - Episode 1",
      "title": "Episode 1",
      "artist": "Undefined",
      "duration": 1060,
      "publishedAt": "2016-02-20T10:11:25.280Z"
    },
    {
      "id": "SQzjzStU1RQ",
      "original_title": "Why dividing by zero is undefined | Functions and their graphs | Algebra II | Khan Academy",
      "title": "Why dividing by zero is undefined | Functions and their graphs | Algebra II | Khan Academy",
      "artist": "",
      "duration": 248,
      "publishedAt": "2013-05-18T10:12:56.581Z"
    }
  ],
  "didyoumean": "",
  "token": "Abc",
  "apikey": "Abc"
}`
const data = JSON.parse(jsonStr)

// 2. 取值,数组索引从0开始,第一项对应索引0
const firstVideoId = data.videos[0].id

// 3. 打印结果
console.log(firstVideoId)

运行后输出结果为:

jbnddQ9l0IA

可选容错处理

如果要避免videos为空、不存在时报错,可以加可选链和空值判断:

const firstVideoId = data?.videos?.[0]?.id ?? ''

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:09:03