如何递归将JSON嵌套对象转为带自定义开闭标记的类标记字符串?
实现方案
核心优化点
- 消除全局变量副作用:改用数组存储每一行输出内容,最后统一拼接为字符串,避免污染全局作用域
- 补充闭合标签:递归处理完嵌套对象的所有子属性后,立即追加对应键名的闭合标记
- 边界兼容:新增null值判断,避免
typeof null === 'object'的语法坑导致运行报错 - 格式适配:自动在顶层对象输出之间插入空行,完全匹配预期输出格式
完整实现代码
const json = { "user": { "first_name": "test", "second_name": "second name", "profile": { "test":{ "img": "img" } } }, "company": { "name": "company 1", "company_nested": { "test" : "test" } } }; function generateTagString(obj) { const lines = []; // 内部递归遍历函数 function iterate(currentObj) { Object.keys(currentObj).forEach((key, index, keyArr) => { const value = currentObj[key]; if (typeof value === 'string') { lines.push(`"${key}": ${value}`); return; } // 排除null的情况,避免typeof null === 'object'的语法坑 if (typeof value === 'object' && value !== null) { // 插入起始标记 lines.push(`##${key}##`); // 递归处理子对象 iterate(value); // 插入闭合标记 lines.push(`##/${key}##`); // 顶层对象之间添加空行 if (keyArr.length > 1 && index !== keyArr.length - 1) { lines.push(''); } } }); } iterate(obj); return lines.join('\n'); } const result = generateTagString(json); // 输出到目标DOM节点 $("#teste").html(result); // 也可以直接打印查看结果 console.log(result);
输出结果
##user## "first_name": test "second_name": second name ##profile## ##test## "img": img ##/test## ##/profile## ##/user## ##company## "name": company 1 ##company_nested## "test": test ##/company_nested## ##/company##
内容的提问来源于stack exchange,提问作者carlos
相关产品推荐
相关产品推荐

