ensure-json
Version:
A <3kB, dependency-free helper that repairs 'almost-JSON' text from LLMs and returns a valid JavaScript object—or throws JsonFixError.
21 lines (18 loc) • 563 B
TypeScript
import { z } from 'zod';
/**
* Error thrown when JSON repair fails.
*/
declare class JsonFixError extends Error {
raw: string;
constructor(msg: string, raw: string);
}
/**
* Attempts to repair and parse "almost-JSON" text from LLMs.
* Optionally validates with a Zod schema.
*/
declare function ensureJson<T = unknown>(raw: string, schema?: z.ZodType<T>): T;
/**
* Async version of ensureJson.
*/
declare function ensureJsonAsync<T = unknown>(raw: string, schema?: z.ZodType<T>): Promise<T>;
export { JsonFixError, ensureJson, ensureJsonAsync };