如何将JSON对象转为无嵌套数组:将leftSection的links转为数组
如何将JSON中嵌套的links对象转换为无嵌套数组?
需求说明
需要将原始JSON结构里leftSection下的links对象,替换为一个仅包含该对象的数组,其余结构保持不变。
原始JSON结构
{ "leftSection": { "contentHtml": { "value": { "de": "Vel ut dicta dolore tractatos" } }, "links": { "link": { "title_de": "Demo Link", "linkMode": "external" } } } }
目标JSON结构
{ "leftSection": { "contentHtml": { "value": { "de": "Vel ut dicta dolore tractatos" } }, "links": [ { "link": { "title_de": "Demo Link", "linkMode": "external" } } ] } }
实现方法(以JavaScript为例)
直接修改leftSection.links的值,把原对象放进一个新数组里即可:
// 假设原始数据存在变量data中 const data = { "leftSection": { "contentHtml": { "value": { "de": "Vel ut dicta dolore tractatos" } }, "links": { "link": { "title_de": "Demo Link", "linkMode": "external" } } } }; // 执行转换 data.leftSection.links = [data.leftSection.links]; // 输出转换后的结果 console.log(JSON.stringify(data, null, 2));
手动转换步骤
如果不需要代码处理,直接编辑JSON文本即可:
- 找到
"links": { ... }这一行 - 把起始大括号
{替换为[ { - 在原
links对象的闭合大括号}后面添加} ]
内容的提问来源于stack exchange,提问作者NeonH
相关产品推荐
相关产品推荐

