MCPcopy Create free account
hub / github.com/QuantiaAI/helm-agents / extractFirstJsonObject

Function extractFirstJsonObject

packages/shared/src/json.ts:18–47  ·  view source on GitHub ↗
(text: string)

Source from the content-addressed store, hash-verified

16 * that inner object.
17 */
18export function extractFirstJsonObject(text: string): unknown {
19 const start = text.indexOf("{");
20 if (start === -1) return undefined;
21
22 let depth = 0;
23 let inString = false;
24 let escaped = false;
25 for (let i = start; i < text.length; i++) {
26 const ch = text[i];
27 if (inString) {
28 if (escaped) escaped = false;
29 else if (ch === "\\") escaped = true;
30 else if (ch === '"') inString = false;
31 continue;
32 }
33 if (ch === '"') inString = true;
34 else if (ch === "{") depth++;
35 else if (ch === "}") {
36 depth--;
37 if (depth === 0) {
38 try {
39 return JSON.parse(text.slice(start, i + 1));
40 } catch {
41 return undefined;
42 }
43 }
44 }
45 }
46 return undefined;
47}

Callers 4

tryParseStructuredFunction · 0.90
tryParseFunction · 0.90
json.test.tsFile · 0.90
tryParseJsonObjectFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected