PHPackages                             edgaras/llm-json-cleaner - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. edgaras/llm-json-cleaner

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

edgaras/llm-json-cleaner
========================

A PHP library that ensures strict JSON extraction and schema validation from LLM API responses, preventing malformed or unexpected output.

v1.1.1(2mo ago)5498↓90.7%MITPHPPHP &gt;=8.3.0

Since Feb 17Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/Edgaras0x4E/LLM-JSON-Cleaner)[ Packagist](https://packagist.org/packages/edgaras/llm-json-cleaner)[ Docs](https://github.com/Edgaras0x4E/LLM-JSON-Cleaner)[ RSS](/packages/edgaras-llm-json-cleaner/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (2)Dependencies (3)Versions (4)Used By (0)

LLM-JSON-Cleaner
================

[](#llm-json-cleaner)

PHP library for sanitizing JSON responses from LLM APIs and validating them against a specified JSON schema.

Features
--------

[](#features)

- **JSON Response Cleaning:** Remove unwanted artifacts.
- **Schema Validation:** Validate and enforce JSON schema constraints.

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

[](#installation)

Install the package via Composer:

```
composer require edgaras/llm-json-cleaner
```

Usage
-----

[](#usage)

### Extracting JSON from LLM Responses

[](#extracting-json-from-llm-responses)

```
require_once 'vendor/autoload.php';

use Edgaras\LLMJsonCleaner\JsonCleaner;

$llmResponse = "Hi there! Please find the details below:\n\n{
    \"task\": \"generate_report\",
    \"parameters\": {
        \"date\": \"2025-02-17\",
        \"format\": \"pdf\"
    }
}\n\nLet me know if you need further assistance.";

// Return JSON only
$extractJson = JsonCleaner::extract($llmResponse, false);
echo $extractJson;
// {"task":"generate_report","parameters":{"date":"2025-02-17","format":"pdf"}}

// Return JSON only as an array
$extractJsonAsArray = JsonCleaner::extract($llmResponse, true);
print_r($extractJsonAsArray);
// (
//  [task] => generate_report
//  [parameters] => Array
//      (
//          [date] => 2025-02-17
//          [format] => pdf
//      )
// )
```

### Cleaning Malformed JSON

[](#cleaning-malformed-json)

`JsonCleaner::extract()` automatically fixes common LLM output issues:

```
// Trailing commas
$json = JsonCleaner::extract('{"name": "Alice", "age": 30,}', true);
// ['name' => 'Alice', 'age' => 30]

// Single-quoted JSON
$json = JsonCleaner::extract("{'name': 'Alice'}", true);
// ['name' => 'Alice']

// Unquoted keys
$json = JsonCleaner::extract('{name: "Alice", active: true}', true);
// ['name' => 'Alice', 'active' => true]

// Multiline string values (literal newlines inside strings)
$json = JsonCleaner::extract('{"text": "line one
line two"}', true);
// ['text' => "line one\nline two"]

// Top-level arrays
$json = JsonCleaner::extract('Here: [{"id":1},{"id":2}] done.', true);
// [['id' => 1], ['id' => 2]]
```

### Validating JSON Against a Schema

[](#validating-json-against-a-schema)

```
require_once 'vendor/autoload.php';

use Edgaras\LLMJsonCleaner\JsonValidator;

$json = '{
  "order_id": 401,
  "customer": "Alice",
  "payment_methods": [
    {
      "method_id": "p1",
      "type": "Credit Card"
    },
    {
      "method_id": "p2",
      "type": "PayPal"
    }
  ]
}';

$schema = [
  'order_id' => ['required', 'integer', 'min:1'],
  'customer' => ['required', 'string'],
  'payment_methods' => ['required', 'array', 'min:1'],
  'payment_methods.*.method_id' => ['required', 'string'],
  'payment_methods.*.type' => ['required', 'string'],
];

$validator = JsonValidator::validateSchema(json_decode($json, 1), $schema);
var_dump($validator);
// bool(true)

$schemaNotFull = [
  'order_id' => ['required', 'integer', 'min:1'],
  'customer' => ['required', 'string'],
];

$validator2 = JsonValidator::validateSchema(json_decode($json, 1), $schemaNotFull);
print_r($validator2);
// Array
// (
//    [0] => Array
//        (
//            [payment_methods] => Array
//                (
//                    [0] => Unexpected field: payment_methods
//                )
//        )
// )
```

### Validation Rules

[](#validation-rules)

RuleDescription`required`Field must be present and non-empty`nullable`Field may be `null` (skips other rules when null)`string`Must be a string`integer`Must be an integer`float`Must be a float or integer`numeric`Must be numeric (int, float, or numeric string)`boolean`Must be a boolean`array`Must be an array`email`Must be a valid email address`url`Must be a valid URL`date`Must be a valid date string`min:N`Minimum value (numbers) or minimum item count (arrays)`max:N`Maximum value (numbers) or maximum item count (arrays)`in:a,b,c`Value must be one of the listed optionsFields without `required` are optional - missing fields won't trigger errors, but present fields are still validated.

Nested array items are validated using wildcard dot notation: `items.*.field_name`

Unexpected fields (not defined in schema) are detected at all nesting levels.

Changelog
---------

[](#changelog)

### v1.1.0

[](#v110)

**JsonCleaner**

- Added automatic trailing comma removal (`{"a": 1,}`)
- Added single-quote to double-quote conversion (`{'key': 'value'}`)
- Added unquoted key detection and quoting (`{key: "value"}`)
- Added multiline string value sanitization (literal newlines inside JSON strings)
- Added top-level JSON array extraction (`[...]` embedded in text)
- All sanitization is string-aware - content inside quoted values is never corrupted

**JsonValidator**

- Added `nullable` rule - allows `null` values and skips further validation
- Added `float` rule - accepts floats and integers
- Added `numeric` rule - accepts any numeric value including numeric strings
- Added `email`, `url`, `date` validation rules
- Added optional field support - fields without `required` don't error when missing
- Added unexpected nested field detection inside wildcard arrays (not just top-level)
- Added sequential array check for wildcard (`.*`) paths - associative arrays are rejected
- Fixed `required` rule to allow `false` boolean values

**General**

- Tested and compatible with PHP 8.4 and PHP 8.5

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance85

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity55

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 ~213 days

Total

3

Last Release

75d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/479996?v=4)[Edgaras](/maintainers/Edgaras)[@edgaras](https://github.com/edgaras)

---

Top Contributors

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

---

Tags

jsonjson-cleanerjson-parserjson-repairjson-sanitizerjson-schemajson-validationjson-validatorllmllm-jsonphpjsonschemavalidatorvalidationcleanerllmgpt

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/edgaras-llm-json-cleaner/health.svg)

```
[![Health](https://phpackages.com/badges/edgaras-llm-json-cleaner/health.svg)](https://phpackages.com/packages/edgaras-llm-json-cleaner)
```

###  Alternatives

[opis/json-schema

Json Schema Validator for PHP

65243.6M302](/packages/opis-json-schema)[ergebnis/json-schema-validator

Provides a JSON schema validator, building on top of justinrainbow/json-schema.

3630.9M7](/packages/ergebnis-json-schema-validator)[johnstevenson/json-works

Create, edit, query and validate json

272.7M6](/packages/johnstevenson-json-works)[evaisse/php-json-schema-generator

A JSON Schema Generator.

20316.0k1](/packages/evaisse-php-json-schema-generator)[dstotijn/yii2-json-schema-validator

A Yii2 extension that provides a validator class for JSON Schema validation.

1730.9k](/packages/dstotijn-yii2-json-schema-validator)

PHPackages © 2026

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