如何使用Python将扁平化JSON转换为嵌套JS对象结构
点分隔扁平JSON转嵌套JS对象实现方案
核心逻辑
- 遍历扁平化对象的所有键值对
- 将每个带点的键按
.拆分为层级路径数组 - 从根对象开始逐层创建嵌套结构,遇到不存在的层级就初始化为空对象
- 最终将值赋值到路径的最后一级节点
完整实现代码
function unflatten(flatObj) { const result = {}; // 遍历所有扁平键值对 for (const dotKey in flatObj) { if (!flatObj.hasOwnProperty(dotKey)) continue; // 拆分层级路径 const keyPath = dotKey.split('.'); let current = result; // 遍历路径,逐层构建嵌套对象 for (let i = 0; i < keyPath.length; i++) { const key = keyPath[i]; // 最后一级路径直接赋值 if (i === keyPath.length - 1) { current[key] = flatObj[dotKey]; break; } // 中间层级不存在则初始化为空对象 if (!current[key] || typeof current[key] !== 'object') { current[key] = {}; } current = current[key]; } } return result; }
使用示例
// 输入扁平化JSON const flatJson = { "profileMenu.info": "Profile information", "profileMenu.infos.generalInfo": "general information", "profileMenu.infos.otherInfos": "Other information" }; const nestedObj = unflatten(flatJson); console.log(nestedObj);
输出结果如下:
{ profileMenu: { info: 'Profile information', infos: { generalInfo: 'general information', otherInfos: 'Other information' } } }
注意事项
- 若存在路径冲突,比如同时存在
a.b: "1"和a: "2",后者会被前者覆盖,使用前请保证你的扁平化JSON的键路径没有逻辑冲突 - 该实现默认所有中间层级都是对象结构,如果需要支持数组格式,可以额外扩展路径中带数字的判断逻辑
内容的提问来源于stack exchange,提问作者burcubelen
相关产品推荐
相关产品推荐

