如何重命名嵌套JSON中含.的对象键为_并解决现有代码报错问题
错误原因
- 调用
JSON.stringify()后得到的是普通字符串,不存在selectionFile属性,执行str.selectionFile.replace时会因为操作undefined的方法直接抛出类型错误。 - 正则表达式匹配逻辑错误,无法覆盖所有键名含
.的场景,还可能误匹配值内容里的字符。
解决方法
方案1:正则替换JSON字符串(简单快速)
适合确认JSON值内容中不会出现"xxx.xxx":格式字符的场景:
const originJson = /* 你的原始JSON对象 */; let jsonStr = JSON.stringify(originJson); // 循环替换键名中的.为_,支持键名含多个.的情况 while (/"([^"]+)\.([^"]+)":/g.test(jsonStr)) { jsonStr = jsonStr.replace(/"([^"]+)\.([^"]+)":/g, (_, p1, p2) => `"${p1}_${p2}":`); } const processedJson = JSON.parse(jsonStr); console.log(processedJson);
方案2:递归遍历对象处理(更稳妥,推荐)
不会误修改值内容中的.,支持任意层级的嵌套结构:
function replaceDotInObjKeys(obj) { // 非对象/空值直接返回 if (typeof obj !== 'object' || obj === null) return obj; // 处理数组类型 if (Array.isArray(obj)) return obj.map(item => replaceDotInObjKeys(item)); // 处理普通对象 const newObj = {}; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { const newKey = key.replace(/\./g, '_'); newObj[newKey] = replaceDotInObjKeys(obj[key]); } } return newObj; } // 调用示例 const originJson = /* 你的原始JSON对象 */; const processedJson = replaceDotInObjKeys(originJson); console.log(processedJson);
内容的提问来源于stack exchange,提问作者JS_basic_knowledge
相关产品推荐
相关产品推荐

