llm-json-extractor
v1.0.0
Published
Extract clean markdown code blocks or structured JSON from conversational, messy, or truncated LLM responses.
Maintainers
Readme
llm-json-extractor
Extract clean code blocks or structured JSON from conversational, messy, or truncated LLM responses.
Features
- 📦 Zero dependencies — Under 800 bytes minified.
- ⚡ Built for Edge — Run in Node.js, Bun, Cloudflare Workers, or Vercel Edge.
- 🛡️ Fully type-safe — Native TypeScript support with generic parsing.
- 🧩 Resilient parsing — Isolates blocks even when cut off or missing closing fences.
Installation
# npm
npm install llm-json-extractor
# pnpm
pnpm add llm-json-extractor
# yarn
yarn add llm-json-extractor
# bun
bun add llm-json-extractorUsage
import { unfenceJson } from 'llm-json-extractor'
// Messy conversational LLM completion
const response = `
Here is the user profile you requested:
\`\`\`json
{
"id": "usr_9982",
"name": "Sarah Jenkins",
"roles": ["admin"]
}
\`\`\`
Let me know if you need anything else!
`
interface User {
id: string
name: string
roles: string[]
}
// Parse messy response into a typed object
const user = unfenceJson<User>(response)
console.log(user.name) // => "Sarah Jenkins"API
| Function | Signature | Returns | Description |
| :--- | :--- | :--- | :--- |
| unfence | (text: string, language?: string) | string | Extracts contents of the first matching code block. |
| unfenceJson | <T>(text: string) | T | Extracts and parses the first JSON block. |
| UnfenceError | class extends Error | Error | Thrown when parsing fails; exposes raw and extracted text. |
