Skip to main content

JSON fixer

const jsonFixer = {
fixJson: function (partialJson) {
try {
// Trim any whitespace from the beginning and end of the string
let fixedJson = partialJson.trim();

// Check if there are any unclosed quotes and close them if needed
const openQuotes = (fixedJson.match(/"/g) || []).length % 2 !== 0;
if (openQuotes) {
fixedJson += '"';
}

// Try to parse the JSON, adding closing braces or brackets as needed
while (true) {
try {
return JSON.parse(fixedJson);
} catch (e) {
// Count the number of opening and closing braces and brackets
const unmatchedCurlyBraces =
(fixedJson.match(/{/g) || []).length -
(fixedJson.match(/}/g) || []).length;
const unmatchedSquareBrackets =
(fixedJson.match(/\[/g) || []).length -
(fixedJson.match(/]/g) || []).length;

// If there are unmatched curly braces, add a closing curly brace
if (unmatchedCurlyBraces > 0) {
fixedJson += "}";
}
// If there are unmatched square brackets, add a closing square bracket
else if (unmatchedSquareBrackets > 0) {
fixedJson += "]";
}
// If the JSON is still invalid, assume there is a missing key-value pair
else {
if (fixedJson[fixedJson.length - 1] === ",") {
fixedJson += '"UNKNOWN_KEY":"VALUE"';
} else {
fixedJson += ',"UNKNOWN_KEY":"VALUE"';
}
}
}
}
} catch (e) {
throw new Error("Unable to fix JSON string");
}
},
};

module.exports = jsonFixer;