如何用JavaScript正则表达式修复无效JSON内容?
正确将类JSON字符串转换为合法JSON的方法
你的问题是把一个非标准的类JSON字符串转换成符合规范的JSON,之前的方法只处理了键的引号,且值的处理会错误地给数字加引号,还无法闭合引号,确实不够规范。下面是可靠的解决思路和代码:
步骤1:给所有未加引号的键添加引号
首先处理对象的键,确保所有键都被双引号包裹:
let input = "{id: 1, name: apple, qty: 2, colors: [{id: 1, hex: #f95}], store: {id: 1, name: Apple Store}}"; // 给键加引号:匹配"键名:"的结构,替换为"键名": let step1 = input.replace(/\b(\w+)\s*:/g, '"$1":'); // 结果:{"id": 1, "name": apple, "qty": 2, "colors": [{"id": 1, "hex": #f95}], "store": {"id": 1, "name": Apple Store}}
步骤2:给需要加引号的字符串值添加引号
接下来处理值部分,只给非数字、非布尔、非null、非数组/对象开头的内容加引号,避免错误包裹数字:
// 匹配": "后面的字符串值,直到遇到,、]、}为止 let step2 = step1.replace(/(?<=: )(?!\d+|true|false|null|\[|\{)([\w#\s]+)(?=,|\]|\})/g, '"$1"'); // 最终结果:{"id": 1, "name": "apple", "qty": 2, "colors": [{"id": 1, "hex": "#f95"}], "store": {"id": 1, "name": "Apple Store"}}
完整代码
把两步合并成一个函数,方便复用:
function convertToValidJSON(str) { // 处理键 let withQuotedKeys = str.replace(/\b(\w+)\s*:/g, '"$1":'); // 处理字符串值 let validJSON = withQuotedKeys.replace(/(?<=: )(?!\d+|true|false|null|\[|\{)([\w#\s]+)(?=,|\]|\})/g, '"$1"'); return validJSON; } // 测试 let input = "{id: 1, name: apple, qty: 2, colors: [{id: 1, hex: #f95}], store: {id: 1, name: Apple Store}}"; let validJSON = convertToValidJSON(input); console.log(validJSON); // 输出:{"id": 1, "name": "apple", "qty": 2, "colors": [{"id": 1, "hex": "#f95"}], "store": {"id": 1, "name": "Apple Store"}}
为什么之前的方法不规范?
- 你用
replaceAll(': ', ': "')会给所有值开头加引号,但没有处理结尾的引号,导致字符串不闭合; - 同时会错误地给数字(比如
1)加上引号,破坏JSON的类型规范; - 无法处理带空格的字符串值(比如
Apple Store),因为你的替换逻辑没有考虑值的结束位置。
内容的提问来源于stack exchange,提问作者Ashta V
相关产品推荐
相关产品推荐

