The string containing JSON with possible trailing junk
The parsed JSON value
Error if no JSON array/object is found or if the JSON is malformed
parseJsonFromDirtyString('[ "a", "b" ]\n&&&\n') // Returns ["a", "b"]
parseJsonFromDirtyString('{"key": "val"} some junk') // Returns {key: "val"}
export function parseJsonFromDirtyString(data: string): unknown {
const trimmed = data.trim();
const openBracket = trimmed.search(/[\[{]/);
if (openBracket === -1) throw new Error("No JSON array or object found in string");
const openChar = trimmed[openBracket];
const closeChar = openChar === "[" ? "]" : "}";
let depth = 0;
let inString = false;
let escaped = false;
for (let i = openBracket; i < trimmed.length; i++) {
const ch = trimmed[i];
if (escaped) {
escaped = false;
continue;
}
if (ch === "\\") {
escaped = true;
continue;
}
if (ch === '"') {
inString = !inString;
continue;
}
if (inString) continue;
if (ch === openChar) depth++;
else if (ch === closeChar) depth--;
if (depth === 0) {
return JSON.parse(trimmed.slice(openBracket, i + 1));
}
}
throw new Error("Unterminated JSON in string");
}
Extracts and parses the first top-level JSON array or object from a string that may contain trailing non-JSON content (e.g. delimiters like "&&&").