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

如何从深度嵌套的JSON字符串中提取extra对象内的id值?

解决方法

步骤1:把JSON字符串转回可操作的JS数据结构

之前误用JSON.stringify把原数组转成了纯文本字符串,第一步必须用JSON.parse将其转回JS对象/数组,才能进行属性访问和遍历:

// 替换成你的目标JSON字符串
const jsonStr = '[{"level1": {"extra": {"id": "aefwwefefwARG@.[t.2"}}, "another": {"level2": {"extra": {"id": "%m6nwefewfqAuo!@"}}}}]';
const data = JSON.parse(jsonStr);

步骤2:递归遍历提取目标id

写一个递归函数,遍历所有嵌套结构,精准定位所有extra对象,筛选出其中字符串类型的id并收集到数组中:

const ids = [];

function extractExtraIds(target) {
  // 处理数组:遍历每个元素递归检查
  if (Array.isArray(target)) {
    target.forEach(item => extractExtraIds(item));
    return;
  }
  // 处理对象:遍历所有属性值
  if (typeof target === 'object' && target !== null) {
    // 检查当前对象是否包含extra,且extra的id是字符串类型
    if (target.extra?.id && typeof target.extra.id === 'string') {
      ids.push(target.extra.id);
    }
    // 递归遍历当前对象的所有属性值
    Object.values(target).forEach(val => extractExtraIds(val));
  }
}

// 执行提取操作
extractExtraIds(data);
console.log(ids); // 输出 ["aefwwefefwARG@.[t.2", "%m6nwefewfqAuo!@", ...]

关键细节

  • 递归逻辑适配任意深度的嵌套结构,不管extra藏在多少层都能被找到
  • 用target.extra?.id可选链操作符,避免因extra不存在导致的报错
  • 额外的类型检查typeof target.extra.id === 'string',确保只收集符合要求的字符串id,过滤掉数字、布尔等无效值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:15:27