How to fix malformed JSON strings in JavaScript? (Asked in technical interview) [closed]

My code:

function fixJson(incompleteJson) {
  let varOcg = incompleteJson.trim();
  try {
    JSON.parse(varOcg);
    return varOcg;
  } catch (e) {
    const quoteRegex = /(w+)(:)/g;
    varOcg = varOcg.replace(quoteRegex, '"$1"$2');
    if (varOcg.endsWith(",")) {
      varOcg = varOcg.slice(0, -1);
    }
    if (!varOcg.endsWith("}") && !varOcg.endsWith("]")) {
      varOcg += "}";
    }
    try {
      JSON.parse(varOcg);
      return varOcg;
    } catch (e) {
      return "Invalid JSON: unable to correct the JSON string.";
    }
  }
}

Sample input 1

input={
  "name": "abc",
  "sub": {
    "sub1": "eng",
    "sub2": "math"
}

output={
  "name": "abc",
  "sub": {
    "sub1": "eng",
    "sub2": "math"
  }
}

Sample input 2

input={
  "name": "abc",
  "sub": {
    "sub1": "eng",
    "sub2": "math
   }
}

output={
  "name": "abc",
  "sub": {
    "sub1": "eng",
    "sub2": "math"
  }
}

I need a function, fixJson, that can handle various issues with malformed JSON, such as:

  • Missing closing braces or brackets
  • Unquoted keys or values
  • Incomplete strings

The function should return the corrected JSON string if possible or an error message if the JSON cannot be fixed.

Here’s what I’m looking for:

  1. A function that attempts to repair common issues with malformed JSON.
  2. It should ensure that the output is valid JSON and formatted correctly.
  3. If the JSON cannot be fixed, it should provide an informative error message.

Could you please help me with the implementation of such a function in JavaScript?

Thanks in advance!