UNPKG

auto-gpt-ts

Version:

my take of Auto-GPT in typescript

81 lines 2.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.correctJson = exports.fixInvalidEscape = void 0; const logging_1 = require("../logging"); const utilities_1 = require("./utilities"); const logger = (0, logging_1.getLogger)('json-utils'); function fixInvalidEscape(jsonToLoad, errorMessage) { while (errorMessage.startsWith("Invalid \\escape")) { const badEscapeLocation = (0, utilities_1.extractCharPosition)(errorMessage); jsonToLoad = jsonToLoad.slice(0, badEscapeLocation) + jsonToLoad.slice(badEscapeLocation + 1); try { JSON.parse(jsonToLoad); return jsonToLoad; } catch (e) { logger.debug("json loads error - fix invalid escape", e); errorMessage = e.toString(); } } return jsonToLoad; } exports.fixInvalidEscape = fixInvalidEscape; function balanceBraces(jsonString) { let openBracesCount = jsonString.split("{").length - 1; let closeBracesCount = jsonString.split("}").length - 1; while (openBracesCount > closeBracesCount) { jsonString += "}"; closeBracesCount++; } while (closeBracesCount > openBracesCount) { jsonString = jsonString.slice(0, jsonString.lastIndexOf("}")); closeBracesCount--; } try { JSON.parse(jsonString); return jsonString; } catch (_a) { return undefined; } } function addQuotesToPropertyNames(jsonString) { const propertyNamePattern = /(\w+):/g; const correctedJsonString = jsonString.replace(propertyNamePattern, (match, p1) => `"${p1}":`); try { JSON.parse(correctedJsonString); return correctedJsonString; } catch (e) { throw e; } } function correctJson(jsonToLoad) { try { JSON.parse(jsonToLoad); return jsonToLoad; } catch (e) { let errorMessage = e.message; if (errorMessage.startsWith("Invalid \\escape")) { jsonToLoad = fixInvalidEscape(jsonToLoad, errorMessage); } if (errorMessage.startsWith("Expecting property name enclosed in double quotes")) { jsonToLoad = addQuotesToPropertyNames(jsonToLoad); try { JSON.parse(jsonToLoad); return jsonToLoad; } catch (e) { errorMessage = e.message; } } const balancedStr = balanceBraces(jsonToLoad); if (balancedStr) { return balancedStr; } } return jsonToLoad; } exports.correctJson = correctJson; //# sourceMappingURL=fix-json-general.js.map