UNPKG

aiwrapper

Version:

A Universal AI Wrapper for JavaScript & TypeScript

69 lines (68 loc) 1.58 kB
import { Jsonic } from "jsonic"; function tryToGetJSONFromText(str) { let startIndex = -1; let endIndex = -1; let expectedClosingBracket; for (let i = 0; i < str.length; i++) { if (str[i] === "{") { expectedClosingBracket = "}"; startIndex = i; break; } if (str[i] === "[") { expectedClosingBracket = "]"; startIndex = i; break; } } if (expectedClosingBracket === void 0) { return null; } for (let i = str.length - 1; i >= 0; i--) { if (str[i] === expectedClosingBracket) { endIndex = i; break; } if (i === 0) { return null; } } if (startIndex === -1 || endIndex === -1) { return null; } return str.slice(startIndex, endIndex + 1); } function extractJSON(str, verbose = false) { const possilbeJsonStr = tryToGetJSONFromText(str); if (possilbeJsonStr === null) { if (verbose) { console.error("Failed to extract JSON from the string: " + str); } return null; } let jsonObj; try { jsonObj = JSON.parse(possilbeJsonStr); } catch (e) { if (verbose) { console.error("Failed to parse JSON"); console.log(possilbeJsonStr); console.log( "Will try to parse it with a less strict JSON parser (jsonic)" ); } try { jsonObj = Jsonic(possilbeJsonStr); } catch (e2) { if (verbose) { console.error("Failed to parse JSON with jsonic as well."); } jsonObj = null; } } return jsonObj; } export { extractJSON as default }; //# sourceMappingURL=extract-json.js.map