如何通过JSONPath路径向嵌套JSON对象添加键值对?
问题需求
给定如下JSON对象data,需通过JSONPath路径$.paths.static.getCountryCode向其中插入指定键值对newConsul,编写JavaScript函数完成该插入操作,最终得到目标结构的对象。
原始数据对象
const data = { "hosts": { "static": { "domain": "http://api-azure-dev.atc.com", "port": 80 }, "azure": { "domain": "http://api-azure-dev.atc-v8.com", "port": 80 } }, "paths": { "static": { "cities": { "hostKey": "static", "path": "/cf/v2/lookups/cities", "method": "GET" } } } };
待插入的键值对
const newConsul = { "hostKey": "azure", "path": "/v8/v1/lookups/countryCode/{country}", "method": "get" };
目标结构
const data = { "hosts": { "static": { "domain": "http://api-azure-dev.atc.com", "port": 80 }, "azure": { "domain": "http://api-azure-dev.atc-v8.com", "port": 80 } }, "paths": { "static": { "cities": { "hostKey": "static", "path": "/cf/v2/lookups/cities", "method": "GET" }, "getCountryCode": { "hostKey": "azure", "path": "/v8/v1/lookups/countryCode/{country}", "method": "get" } } } };
实现方案
方案1:固定路径直接赋值
如果路径固定不变,直接通过对象属性链赋值最简洁,同时加入空值判断避免报错:
function insertKeyValue(data, key, value) { // 确保路径上的各级对象存在 if (!data.paths) data.paths = {}; if (!data.paths.static) data.paths.static = {}; data.paths.static[key] = value; } // 调用函数完成插入 insertKeyValue(data, 'getCountryCode', newConsul);
方案2:通用JSONPath解析插入
如果需要支持任意JSONPath路径(后续路径可能变动),可以编写通用解析函数:
function insertByJsonPath(obj, jsonPath, value) { // 处理路径,去除开头的$并分割为片段 const segments = jsonPath.replace(/^\$./, '').split('.'); let current = obj; // 遍历路径片段(除最后一个),确保中间层级对象存在 for (let i = 0; i < segments.length - 1; i++) { const segment = segments[i]; if (!current[segment]) { current[segment] = {}; } current = current[segment]; } // 给最后一个路径节点赋值 const lastSegment = segments[segments.length - 1]; current[lastSegment] = value; } // 调用函数完成插入 insertByJsonPath(data, '$.paths.static.getCountryCode', newConsul);
验证
调用上述任意函数后,打印data即可确认结构与目标一致。
内容的提问来源于stack exchange,提问作者Shubham Shaw
相关产品推荐
相关产品推荐

