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

TypeScript如何提取JSON中任意层级所有text键的对应值

解决方法

你可以通过递归深度遍历JSON所有层级的方式提取所有text键的值,实现逻辑和可直接使用的代码如下:


实现逻辑

  • 编写递归函数遍历每一层数据,同时兼容对象、数组两种复合类型
  • 每次遍历到普通对象时,先检查是否存在text键,存在就把对应值存入结果集
  • 遍历当前层级所有子元素,重复执行上述检查逻辑,直到所有层级遍历完成

可运行代码示例

// 提取所有层级text值的工具函数
function getAllText(target) {
  const textList = [];

  // 内部递归遍历方法
  function traverse(node) {
    // 基础类型/空值直接跳过
    if (!node || typeof node !== "object") return;

    // 数组场景:遍历每一项递归
    if (Array.isArray(node)) {
      node.forEach(item => traverse(item));
      return;
    }

    // 普通对象场景:先检查是否有text属性
    if ("text" in node) {
      textList.push(node.text);
    }
    // 遍历对象所有属性值递归
    Object.values(node).forEach(val => traverse(val));
  }

  traverse(target);
  return textList;
}

// 使用示例
// 先把你的JSON字符串转为JS对象
const jsonData = JSON.parse('你的JSON字符串');
const result = getAllText(jsonData);
console.log(result);
/* 输出对应你给出的示例JSON结果:
[
  "this is a simple page, about a simple umbrella.",
  "you can use this text to find the umbrella page.",
  "do you like it?"
]
*/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:06:04