如何解析API返回的无引号键对象数组字符串?
问题:解析无引号键的类JSON字符串
我从API获取到一段类JSON格式的字符串,但对象的键未添加引号,无法直接用JSON.parse()解析。字符串内容如下:
'[ { q: "What does DSA stand for?", o1: "Data Structure Algorithm", o2: "Data Structure and Architecture", o3: "Dynamic System Analysis", o4: "Digital System Automation" }, { q: "What is the primary goal of Object-Oriented Programming?", o1: "Efficiency", o2: "Code reusability", o3: "Low memory usage", o4: "Shorter development time" }, { q: "Explain the concept of inheritance in OOP.", }, { q: "What is the time complexity of searching in a binary search tree?", }, { q: "Write a function to check if a given string is a palindrome.", }, { q: "Given a sorted array, find the index of a specific element using binary search.", }, { q: "Implement a queue data structure using stacks.", } ]'
我尝试了以下代码,但未能成功解析:
// Remove line breaks and leading/trailing whitespace const cleanedResponse = response.replace(/\s+/g, ''); // Convert keys to strings (double quotes) const jsonString = cleanedResponse.replace(/([a-zA-Z0-9_]+):/g, '"$1":'); // Convert single quotes to double quotes (for property values) const validJsonString = jsonString.replace(/'([^']+)'/g, '"$1"'); console.log(JSON.parse(validString));
解决方案
你的代码存在几处关键问题,修正后即可正常解析:
- 变量名不匹配:最后解析用的
validString和前面定义的validJsonString不一致 - 未处理HTML转义字符:字符串中的
"是HTML转义的双引号,需先转为真实的" - 未移除首尾单引号:原始字符串被单引号包裹,不符合JSON格式要求
- 未清理对象末尾的多余逗号:JSON不允许属性列表最后一项后保留逗号
修正后的完整代码:
// 假设response是API返回的原始字符串 const response = `'[ { q: "What does DSA stand for?", o1: "Data Structure Algorithm", o2: "Data Structure and Architecture", o3: "Dynamic System Analysis", o4: "Digital System Automation" }, { q: "What is the primary goal of Object-Oriented Programming?", o1: "Efficiency", o2: "Code reusability", o3: "Low memory usage", o4: "Shorter development time" }, { q: "Explain the concept of inheritance in OOP.", }, { q: "What is the time complexity of searching in a binary search tree?", }, { q: "Write a function to check if a given string is a palindrome.", }, { q: "Given a sorted array, find the index of a specific element using binary search.", }, { q: "Implement a queue data structure using stacks.", } ]'`; // 1. 移除首尾的包裹单引号 const withoutWrapQuotes = response.replace(/^'|'$/g, ''); // 2. 把HTML转义的"转为真实双引号 const unescaped = withoutWrapQuotes.replace(/"/g, '"'); // 3. 清理对象末尾的多余逗号 const cleanedCommas = unescaped.replace(/\s*,\s*}/g, '}'); // 4. 给无引号的键添加双引号 const validJson = cleanedCommas.replace(/([a-zA-Z0-9_]+):/g, '"$1":'); // 5. 解析JSON并输出 try { const parsedData = JSON.parse(validJson); console.log(parsedData); } catch (err) { console.error('解析失败:', err); }
关键修复说明
- 移除包裹单引号:原始字符串首尾的单引号不属于JSON结构,必须先剔除
- 转义HTML实体:
"是HTML对双引号的转义,需还原为"才能被JSON识别 - 清理多余逗号:JSON语法严格禁止属性列表末尾保留逗号,否则会触发解析错误
- 统一变量名:确保解析时使用的变量和前面处理后的变量名一致
内容的提问来源于stack exchange,提问作者SaifUllah
相关产品推荐
相关产品推荐

