I'm getting a response from an api in string form like this:
'[
{
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.",
}
]'.
And want to parse it and get key-values from it. The problem here is that the keys are not in quotations, so difficult to parse it using JSON.parse()
was trying:
// 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));
and expecting this to parse the string.