json-restructure
Version:
A TypeScript library for repairing malformed JSON strings
38 lines • 1.2 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.repairJson = void 0;
function repairJson(jsonString) {
const commentRegex = /(?:\/\/.*|\/\*[\s\S]*?\*\/)/g;
const jsonWithoutComments = jsonString.replace(commentRegex, '');
const fixedJson = jsonWithoutComments.replace(/,\s*([\]}])/g, '$1');
const fixedJsonWithBraces = addMissingBraces(fixedJson);
return fixedJsonWithBraces;
}
exports.repairJson = repairJson;
function addMissingBraces(jsonString) {
let countOpenBraces = 0;
let countOpenBrackets = 0;
for (const char of jsonString) {
if (char === '{') {
countOpenBraces++;
}
else if (char === '[') {
countOpenBrackets++;
}
else if (char === '}') {
countOpenBraces--;
}
else if (char === ']') {
countOpenBrackets--;
}
}
let fixedJson = jsonString;
for (let i = 0; i < countOpenBraces; i++) {
fixedJson += '}';
}
for (let i = 0; i < countOpenBrackets; i++) {
fixedJson += ']';
}
return fixedJson;
}
//# sourceMappingURL=jsonRepair.js.map
;