UNPKG

json-restructure

Version:

A TypeScript library for repairing malformed JSON strings

30 lines 1.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.repairJson = void 0; function repairJson(jsonString) { try { // Try parsing the JSON string first JSON.parse(jsonString); // If no error is thrown, the JSON is valid, so return the original string return jsonString; } catch (error) { // If an error occurs during parsing, attempt to repair the JSON string const repairedJson = repairJsonString(jsonString); return repairedJson; } } exports.repairJson = repairJson; function repairJsonString(jsonString) { const regex = /("[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'|\/\*[\S\s]*?\*\/|\/\/[^\n]*)/g; const replacer = (match) => { if (/^\/\//.test(match)) return ''; if (/^\/\*/.test(match)) return ''; return match; }; const repairedJson = jsonString.replace(regex, replacer); return repairedJson; } //# sourceMappingURL=jsonRepair.js.map