PHPackages                             teariot/json-repair - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. teariot/json-repair

ActiveLibrary[Database &amp; ORM](/categories/database)

teariot/json-repair
===================

Repair broken, malformed, or non-standard JSON — fix quotes, commas, comments, Python constants, JSONP, NDJSON, HTML entities, and more

1.0.2(1mo ago)01↑2900%MITPHPPHP &gt;=8.0

Since Mar 24Pushed 1mo agoCompare

[ Source](https://github.com/TeaRiot/JsonRepair)[ Packagist](https://packagist.org/packages/teariot/json-repair)[ RSS](/packages/teariot-json-repair/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (4)Used By (0)

teariot/json-repair
===================

[](#teariotjson-repair)

PHP 8.0+ library to repair broken, malformed, or non-standard JSON.

Handles real-world garbage: LLM responses with `` blocks, truncated output, single quotes, trailing commas, comments, JSONP, Python constants, MongoDB types, HTML entities, and more.

Installation
------------

[](#installation)

```
composer require teariot/json-repair
```

Quick Start
-----------

[](#quick-start)

```
use Teariot\JsonRepair\JsonRepair;

// Fix broken JSON
$json = JsonRepair::fix("{name: 'John', age: 30,}");
// → {"name":"John","age":30}

// Fix and decode in one call
$data = JsonRepair::decode("{active: True, tags: ['php', 'json',]}");
// → ['active' => true, 'tags' => ['php', 'json']]
```

Extract JSON from Text
----------------------

[](#extract-json-from-text)

Pull JSON out of LLM responses, log lines, or any surrounding text:

```
// From LLM response with  block
$raw = 'Analyzing the query... {"result": true, "score": 42}';
$json = JsonRepair::extractAndFix($raw);
// → {"result":true,"score":42}

// From log line
$log = '[2024-03-24 13:17:52] production.WARNING: Response: {"status": "ok"}';
$json = JsonRepair::extractAndFix($log);
// → {"status":"ok"}

// From markdown code block
$md = "```json\n{\"a\": 1}\n```";
$json = JsonRepair::extractAndFix($md);
// → {"a":1}

// From plain text
$text = "Here is the analysis result:\n\n{\"mentioned\": true, \"tone\": \"positive\"}";
$json = JsonRepair::extractAndFix($text);
// → {"mentioned":true,"tone":"positive"}
```

Template: Fill Missing Keys
---------------------------

[](#template-fill-missing-keys)

When LLM output is truncated or incomplete, apply a template to ensure all expected keys exist:

```
$template = [
    'mentioned'    => false,
    'occurrences'  => [],
    'position'     => null,
    'tone'         => 'non',
    'comment'      => null,
    'other_brands' => [],
];

// Truncated JSON — missing keys filled from template
$data = JsonRepair::fixWithTemplate(
    '{"mentioned": true, "tone": "negative"',
    $template
);
// → ['mentioned' => true, 'tone' => 'negative', 'occurrences' => [], 'position' => null, ...]

// Extract + fix + decode + template in one call
$data = JsonRepair::extractAndDecode(
    'reasoning {"mentioned": true, "tone": "negative"}',
    $template
);
```

What It Fixes
-------------

[](#what-it-fixes)

ProblemInputOutputUnquoted keys`{name: "John"}``{"name":"John"}`Single quotes`{'a': 'b'}``{"a":"b"}`Smart/curly quotes`{"a": "b"}``{"a":"b"}`Backtick quotes`{`a`: `b`}``{"a":"b"}`Trailing commas`{"a": 1,}``{"a":1}`Leading commas`{,"a": 1}``{"a":1}`Missing commas`{"a": 1 "b": 2}``{"a":1,"b":2}`Missing colons`{"a" 1}``{"a":1}`Missing brackets`{"a": 1``{"a":1}`Redundant brackets`{"a": 1}}``{"a":1}`Block comments`{"a": 1 /* x */}``{"a":1}`Line comments`{"a": 1 // x}``{"a":1}`Hash comments`{"a": 1 # x}``{"a":1}`JSONP`callback({"a": 1});``{"a":1}`Markdown fences````json{"a":1}`````{"a":1}`Python True/False/None`{a: True, b: None}``{"a":true,"b":null}`JS undefined/NaN`undefined``null`String concatenation`"a" + "b"``"ab"`Ellipsis`[1, 2, ...]``[1,2]`Leading zero numbers`0123``"0123"`Truncated JSON`{"a":``{"a":null}`NDJSON`{"a":1}\n{"b":2}``[{"a":1},{"b":2}]`Regex literals`/test/gi``"/test/gi"`MongoDB types`ObjectId("abc")``"abc"`HTML entities`"a &amp; b"``"a & b"``` blocks`... {}``{}`Log prefixes`[date] level: {}``{}`Full API
--------

[](#full-api)

### Static Facade

[](#static-facade)

```
use Teariot\JsonRepair\JsonRepair;

// Core
JsonRepair::fix(string $input, bool $beautify = false): string
JsonRepair::decode(string $input, bool $assoc = true, int $depth = 512, int $flags = 0): mixed
JsonRepair::tryFix(string $input, bool $beautify = false): string      // never throws
JsonRepair::needsRepair(string $input): bool

// Extract from text
JsonRepair::extractAndFix(string $raw, bool $beautify = false): string
JsonRepair::extractAndDecode(string $raw, ?array $template = null, bool $assoc = true): mixed

// Template
JsonRepair::fixWithTemplate(string $input, array $template): array

// Streaming (memory-efficient for large files)
JsonRepair::stream($source, int $chunkSize = 65536, bool $beautify = false): Generator
JsonRepair::streamCollect($source, int $chunkSize = 65536, bool $beautify = false): string
```

### Helper Functions

[](#helper-functions)

```
use function Teariot\JsonRepair\json_repair;
use function Teariot\JsonRepair\json_repair_decode;
use function Teariot\JsonRepair\json_try_repair;
use function Teariot\JsonRepair\json_extract_and_fix;
use function Teariot\JsonRepair\json_extract_and_decode;
use function Teariot\JsonRepair\json_fix_with_template;
use function Teariot\JsonRepair\json_repair_stream;
```

Streaming
---------

[](#streaming)

Process large JSON files without loading everything into memory:

```
$handle = fopen('large.json', 'r');
foreach (JsonRepair::stream($handle) as $chunk) {
    echo $chunk;
}
fclose($handle);

// Or collect into a string
$handle = fopen('large.json', 'r');
$json = JsonRepair::streamCollect($handle);
fclose($handle);
```

Requirements
------------

[](#requirements)

- PHP &gt;= 8.0
- ext-json
- ext-mbstring
- ext-ctype

Testing
-------

[](#testing)

```
composer install
vendor/bin/phpunit
```

License
-------

[](#license)

MIT

###  Health Score

38

—

LowBetter than 84% of packages

Maintenance98

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

46d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6f6607a58ba1ad9fbbdcdf6566b2300b87e38135e8697bebe5a5883b6034eebe?d=identicon)[TeaRiot](/maintainers/TeaRiot)

---

Top Contributors

[![TeaRiot](https://avatars.githubusercontent.com/u/148728335?v=4)](https://github.com/TeaRiot "TeaRiot (4 commits)")

---

Tags

jsonstreamingNDJSONtemplateparseextractmongodbpythoncommentsllminvalidfixbrokenrepairmalformedJSONP

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/teariot-json-repair/health.svg)

```
[![Health](https://phpackages.com/badges/teariot-json-repair/health.svg)](https://phpackages.com/packages/teariot-json-repair)
```

###  Alternatives

[mongodb/mongodb

MongoDB driver library

1.6k64.0M543](/packages/mongodb-mongodb)[clue/ndjson-react

Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.

15267.7M16](/packages/clue-ndjson-react)[apix/cache

A thin PSR-6 cache wrapper with a generic interface to various caching backends emphasising cache taggging and indexing to Redis, Memcached, PDO/SQL, APC and other adapters.

114542.8k6](/packages/apix-cache)[moloquent/moloquent

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

120114.6k7](/packages/moloquent-moloquent)[denchikby/phalcon-mongodb-odm

Phalcon MongoDB ODM

4212.8k](/packages/denchikby-phalcon-mongodb-odm)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
