(text: string)
| 16 | * that inner object. |
| 17 | */ |
| 18 | export 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 | } |
no outgoing calls
no test coverage detected