npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@braingrid/json-guard

v0.1.1

Published

Schema-aware JSON repair engine for LLM output recovery and user input validation

Readme

@braingrid/json-guard

Schema-aware JSON repair engine for LLM output recovery and user input validation

A minimal, pluggable JSON repair engine designed to recover malformed AI outputs into schema-valid JSON.

Philosophy: "Repair what's broken, validate it, no modes, no profiles — just JSON that works."

Features

  • 🔧 Automatic Repair - Fixes common JSON syntax errors from AI outputs
  • 📐 Schema-Driven - Uses JSON Schema (Ajv) or Zod for validation
  • 🔌 Pluggable - Extensible with custom repair strategies
  • 🎯 Type-Safe - Full TypeScript support with generics
  • 🚀 Dual Package - ESM and CJS support

Installation

pnpm add @braingrid/json-guard
# or
npm install @braingrid/json-guard
# or
yarn add @braingrid/json-guard

Quick Start

import { createGuard, ajvAdapter } from "@braingrid/json-guard";

// Define your schema
const schema = ajvAdapter().fromJsonSchema({
  type: "object",
  required: ["action"],
  properties: {
    action: { enum: ["search", "create", "delete"] },
    limit: { type: "integer", default: 10 }
  },
  additionalProperties: false
});

// Create a guard
const guard = createGuard();

// Repair malformed AI output
const result = await guard.repair(
  "```json\n{ action:'Search', limit:'10', extra:true }\n```",
  { schema }
);

console.log(result.value);
// => { action: "search", limit: 10 }

API

createGuard()

Creates a new Guard instance with all default strategies registered.

const guard = createGuard();

guard.repair<T>(rawInput: string, options: RepairOptions): Promise<GuardResult<T>>

Repairs malformed JSON against a schema.

Parameters:

  • rawInput (string, required) - The potentially malformed JSON string
  • options.schema (SchemaAdapter, required) - Schema adapter for validation
  • options.defaultStrategies (string[], optional) - List of built-in strategies to apply
  • options.customStrategies (Strategy[], optional) - User-defined strategies to run after defaults

Returns: Promise<GuardResult<T>>

interface GuardResult<T = unknown> {
  ok: boolean;                  // Whether repair succeeded
  value?: T;                    // Parsed and validated value
  json?: string;                // Repaired JSON string
  diagnostics: Diagnostic[];    // Repair diagnostics
  confidence: number;           // Confidence score (0-1)
}

Built-In Strategies

The following strategies run in order by default:

  1. extractJsonBlock - Extracts JSON from markdown code blocks or surrounding text
  2. tolerantParse - Fixes single quotes, unquoted keys, trailing commas, comments
  3. separatorNormalizer - Fixes separator issues (semicolons, missing commas)
  4. bracketAndQuoteFixer - Adds missing closing brackets and quotes
  5. schemaAlign - Type coercion, enum normalization, default values
  6. sanitizers - Removes disallowed properties per schema
  7. finalize - Final validation and serialization

Schema Adapters

Ajv (JSON Schema)

import { ajvAdapter } from "@braingrid/json-guard";

const schema = ajvAdapter().fromJsonSchema({
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "number" }
  }
});

Zod

import { zodAdapter } from "@braingrid/json-guard";
import { z } from "zod";

const schema = zodAdapter().fromZodSchema(
  z.object({
    name: z.string(),
    age: z.number()
  })
);

Custom Strategies

Create custom strategies to handle domain-specific repairs:

import type { Strategy } from "@braingrid/json-guard";

const aliasKeys: Strategy = {
  name: "aliasKeys",
  async apply({ value }) {
    if (value && typeof value === "object" && "firstname" in value) {
      return {
        value: { ...value, name: value.firstname },
        diagnostics: [{
          severity: "info",
          message: "Mapped 'firstname' to 'name'",
          strategy: "aliasKeys"
        }]
      };
    }
    return { diagnostics: [] };
  }
};

const result = await guard.repair(rawInput, {
  schema,
  customStrategies: [aliasKeys]
});

Selective Strategy Usage

Disable specific default strategies:

import { DEFAULT_STRATEGIES } from "@braingrid/json-guard";

const result = await guard.repair(rawInput, {
  schema,
  defaultStrategies: DEFAULT_STRATEGIES.filter(
    s => s !== "separatorNormalizer"
  )
});

Examples

Markdown-Wrapped JSON

const input = '```json\n{"name": "test"}\n```';
const result = await guard.repair(input, { schema });
// Extracts and validates the JSON

Single Quotes & Unquoted Keys

const input = "{name: 'test', active: true}";
const result = await guard.repair(input, { schema });
// Fixes to: {"name": "test", "active": true}

Enum Case Normalization

const input = '{"action": "CREATE"}';  // Wrong case
const result = await guard.repair(input, { schema });
// Normalizes to: {"action": "create"}

Type Coercion

const input = '{"age": "30"}';  // String instead of number
const result = await guard.repair(input, { schema });
// Coerces to: {"age": 30}

TypeScript Types

import type {
  Guard,
  GuardResult,
  Strategy,
  SchemaAdapter,
  Diagnostic
} from "@braingrid/json-guard";

License

Apache-2.0

Contributing

Contributions welcome! Please see the main repository for contribution guidelines.