llm-json-parse
v0.1.1
Published
Extract and repair JSON from noisy LLM text output (code fences, trailing commas, single quotes, extra prose). Zero dependencies, TypeScript-first.
Downloads
282
Maintainers
Readme
llm-json-parse
Extract and repair JSON from noisy LLM text output. Zero dependencies, TypeScript-first.
LLMs rarely return perfectly clean JSON. You usually get things like:
Sure! Here's the data you asked for:
```json
{
"name": "Ada",
"tags": ["a", "b",],
}
```
Let me know if you need anything else!llm-json-parse strips the fences and prose, extracts the JSON span, and repairs common
mistakes (trailing commas, single quotes, unquoted keys) so JSON.parse doesn't blow up.
Install
npm install llm-json-parseUsage
import { parseLLMJson, safeParseLLMJson } from "llm-json-parse";
const text = await callYourLLM();
// Throws LLMJsonParseError if it truly can't be parsed
const data = parseLLMJson<{ name: string; tags: string[] }>(text);
// Or, never throws:
const result = safeParseLLMJson(text);
if (result.success) {
console.log(result.data);
} else {
console.error(result.error);
}What it handles
- Markdown code fences (
```json ... ```, or plain``` ... ```) - Extra prose before/after the JSON ("Sure, here's the result: {...} Let me know!")
- Trailing commas (
{"a": 1,}) - Single-quoted strings (
{'a': 'b'}) - Unquoted object keys (
{a: 1}) - Braces/brackets inside string values (won't confuse the extractor)
API
parseLLMJson<T>(input: string, options?: ParseOptions): T
Parses and returns the JSON value. Throws LLMJsonParseError if parsing fails.
safeParseLLMJson<T>(input: string, options?: ParseOptions): SafeParseResult<T>
Never throws. Returns { success, data, error }.
ParseOptions
{ repair?: boolean } // default: true — set false to disable lenient repairsLicense
MIT
