Repair invalid JSON strings by automatically fixing common syntax errors like single quotes, unquoted keys, trailing commas, and missing brackets.
- PHP 8.3+
composer require cortexphp/json-repairuse Cortex\JsonRepair\JsonRepairer;
use function Cortex\JsonRepair\json_repair;
use function Cortex\JsonRepair\json_repair_decode;
// Broken JSON (single quotes, unquoted keys, trailing comma)
$broken = "{'name': 'John', age: 30, active: true,}";
$repaired = (new JsonRepairer($broken))->repair();
// {"name": "John", "age": 30, "active": true}
// Or use the helper function
$repaired = json_repair($broken);
// Repair and decode in one step
$data = (new JsonRepairer($broken))->decode();
// ['name' => 'John', 'age' => 30, 'active' => true]
// Or use the helper function
$data = json_repair_decode($broken);When repairing JSON from streaming sources (e.g., LLM responses), you may want to remove keys with missing values instead of adding empty strings:
// Missing value - defaults to adding empty string
$broken = '{"name": "John", "age": }';
$repaired = json_repair($broken);
// {"name": "John", "age": ""}
// Remove keys with missing values
$repaired = json_repair($broken, omitEmptyValues: true);
// {"name": "John"}Similarly, you can remove keys with incomplete string values instead of closing them:
// Incomplete string - defaults to closing the string
$broken = '{"name": "John", "bio": "A developer who';
$repaired = json_repair($broken);
// {"name": "John", "bio": "A developer who"}
// Remove keys with incomplete strings
$repaired = json_repair($broken, omitIncompleteStrings: true);
// {"name": "John"}Both options can be used together, which is especially useful for streaming JSON where deltas are concatenated:
$broken = '{"name": "John", "age": , "bio": "A developer who';
$repaired = json_repair($broken, omitEmptyValues: true, omitIncompleteStrings: true);
// {"name": "John"}You can also pass these options to the JsonRepairer constructor:
$repairer = new JsonRepairer(
$broken,
ensureAscii: true,
omitEmptyValues: true,
omitIncompleteStrings: true
);
$repaired = $repairer->repair();Or with json_repair_decode:
$data = json_repair_decode(
$broken,
omitEmptyValues: true,
omitIncompleteStrings: true
);The library supports PSR-3 logging for debugging repair operations. Pass any PSR-3 compatible logger to see what repairs are being made:
use Psr\Log\LoggerInterface;
// Using the helper function
$repaired = json_repair($broken, logger: $logger);
// Using the class (implements LoggerAwareInterface)
$repairer = new JsonRepairer($broken);
$repairer->setLogger($logger);
$repaired = $repairer->repair();Log messages include the position in the JSON string and a context snippet showing where the repair occurred. This is useful for:
- Debugging why certain repairs are being made
- Understanding how malformed JSON is being interpreted
- Tracking repair operations in production environments
The MIT License (MIT). Please see License File for more information.