0

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.

Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31
  • 3
    Where is this coming from? Can you ask them to use a standard format like JSON? – Barmar Sep 01 '23 at 15:04
  • 2
    Trying to clean up invalid JSON is not going to be robust. What if one of the strings contains `foo:`? – Barmar Sep 01 '23 at 15:05
  • 1
    https://stackoverflow.com/a/61600026/5334486 <- `JSON5 is a superset of JSON that allows ES5 syntax, including unquoted property keys.` here is a fiddle: https://jsfiddle.net/94sg85ep/ – GrafiCode Sep 01 '23 at 15:07

0 Answers0