如何使用TypeScript结合JSONPath获取JSON子节点并替换内容?
我来帮你梳理下如何用JSONPath定位JSON节点,再用TypeScript完成内容替换的方案,结合你给出的示例JSON一步步说明:
1. 先用JSONPath定位目标节点
先根据你的需求确定对应的JSONPath表达式,针对你的示例JSON,常用的定位方式如下:
- 获取India的Attributes中的Time:
$.India.Attributes.Time - 获取ActiveCity的profile值:
$.India.ActiveCity.profile - 获取CurrentCities下所有城市的population:
$.India.CurrentCities.*.population - 获取FeatureCities里的NewDelhi节点:
$.India.FeatureCities.NewDelhi - 递归获取所有层级的population(如果有嵌套更深的情况):
$..population
2. TypeScript实现替换的具体步骤
原生JavaScript/TypeScript没有内置JSONPath支持,所以我们可以用成熟的第三方库jsonpath-plus(自带TypeScript类型定义)来实现节点查询和修改。
步骤1:安装依赖
在项目中执行命令安装:
npm install jsonpath-plus @types/jsonpath-plus
步骤2:编写替换逻辑
下面是两个常见场景的代码示例:
场景1:替换单个节点的值
比如把CurrentCities中Mumbai的population替换为新数值:
import { JSONPath } from 'jsonpath-plus'; // 你的示例JSON数据 const indiaData = { "India":{ "Attributes":{"Time":"2006-05-04T03:22:11.499Z"}, "ActiveCity":{ "profile":"Mumbai" }, "CurrentCities":{ "Mumbai":{"population":"121212121","Area":8}, "Delhi":{"population":"121212121","Area":8}, "Lonng":{"population":"121212121","Area":8} }, "FeatureCities":{ "NewMumbai":{"population":"121212121","Area":8}, "NewDelhi":{"population":"121212121","Area":8}, "NewLonng":{"population":"121212121","Area":8} } } }; // 用JSONPath定位目标节点,返回JSON Pointer格式的路径 const targetPointers = JSONPath({ path: "$.India.CurrentCities.Mumbai.population", json: indiaData, resultType: "pointer" }); // 修改目标节点的值 if (targetPointers.length > 0) { const keys = targetPointers[0].slice(1).split('/'); // 解析JSON Pointer为键数组 let currentNode = indiaData; // 遍历到目标节点的父节点 for (let i = 0; i < keys.length - 1; i++) { currentNode = currentNode[keys[i]]; } // 替换值 currentNode[keys[keys.length - 1]] = "150000000"; } console.log(indiaData.India.CurrentCities.Mumbai.population); // 输出: "150000000"
场景2:批量替换多个节点的值
比如把CurrentCities下所有城市的Area统一替换为10:
// 定位所有CurrentCities下城市的Area节点 const areaPointers = JSONPath({ path: "$.India.CurrentCities.*.Area", json: indiaData, resultType: "pointer" }); // 遍历每个节点替换值 areaPointers.forEach(pointer => { const keys = pointer.slice(1).split('/'); let currentNode = indiaData; for (let i = 0; i < keys.length - 1; i++) { currentNode = currentNode[keys[i]]; } currentNode[keys[keys.length - 1]] = 10; }); console.log(indiaData.India.CurrentCities); // 输出的每个城市的Area字段都会变成10
3. 关键注意事项
- 使用
resultType: "pointer"是核心:它返回的JSON Pointer可以直接定位到原数据的节点,让我们能直接修改原JSON对象;如果用默认的value类型,只能拿到节点值,无法直接修改原数据。 - TypeScript类型安全:如果需要更严格的类型检查,可以为你的JSON数据定义接口,避免使用
any类型。比如:
interface City { population: string; Area: number; } interface CountryData { India: { Attributes: { Time: string }; ActiveCity: { profile: string }; CurrentCities: Record<string, City>; FeatureCities: Record<string, City>; }; } const indiaData: CountryData = { /* 你的数据 */ };
- 灵活使用JSONPath通配符:
*匹配任意子节点,..递归遍历所有层级,能应对结构动态变化的JSON数据。
内容的提问来源于stack exchange,提问作者Thyag web
相关产品推荐
相关产品推荐

