Skip to content

Examples

Analyse a failed import (targeted repair)

Log uploads and partner feeds often fail with almost-valid JSON. Analyse first so you only apply the repairs that matter:

php
$upload = file_get_contents('/tmp/partner-feed.json');

$report = JsonFast::analyse($upload);

if ($report['valid']) {
    $data = JsonFast::minify($upload);
} elseif (!$report['repairable']) {
    throw new RuntimeException($report['error']['message']);
} else {
    $flags = array_reduce(
        $report['repairs'],
        fn ($mask, $r) => $mask | $r['bit'],
        0
    );

    logger()->info('Repairing feed', [
        'line' => $report['error']['line'],
        'column' => $report['error']['column'],
        'flags' => array_column($report['repairs'], 'flag'),
    ]);

    $data = JsonFast::repair($upload, $flags);
}

Unwrap API responses stored as JSON strings

php
// Decodes to a string, not an array — classic double-encoding
$raw = $httpClient->get('/v1/config')->getBody();
$outer = json_decode($raw, true);

$config = JsonFast::unwrap($outer['data'], maxDepth: 3);
// Now a real array/object graph, not nested strings

Triple-wrapped webhook body:

php
$body = $request->getContent();
// "\"{\\\"event\\\":\\\"order.created\\\"}\""
$event = JsonFast::unwrap($body, maxDepth: 5, output: JsonFast::OUTPUT_OBJECT);
echo $event->event; // order.created

Repair real-world JSON

When you want every repair flag in one shot:

php
$broken = <<<'JSON'
{
    // user profile
    "name": Allan,
    "active": true,
}
JSON;

$fixed = JsonFast::repair($broken, JsonFast::REPAIR_ALL, JsonFast::OUTPUT_STRING);

Inspect invalid JSON (lightweight check)

When you only need pass/fail and error position — no repair suggestions:

php
$report = JsonFast::inspect($invalidJson);
// validation status with error line/column when invalid

Extract multiple paths

php
$result = JsonFast::extract($json, ['user.name', 'user.email', 'missing']);
// ['user.name' => 'Allan', 'user.email' => '...', 'missing' => null]
php
$emails = JsonFast::search($json, 'users[*].email');
// ['allan@example.com', 'bob@example.com']

Schema workflow

php
$schema = JsonFast::getSchema($json, JsonFast::OUTPUT_STRING);

$result = JsonFast::validateSchema($json, $schema);
/*
[
    'valid' => false,
    'errors' => ['$.id expected integer, got string'],
]
*/

$clean = JsonFast::applySchema($json, $schema);

Structural diff

php
$changes = JsonFast::diff(
    '{"name":"Allan","active":true}',
    '{"name":"Allan","active":false,"role":"admin"}'
);
/*
[
    'added' => ['$.role' => 'admin'],
    'removed' => [],
    'changed' => [
        '$.active' => ['from' => true, 'to' => false],
    ],
]
*/

Formatting

php
$pretty = JsonFast::beautify($json, indent: 4, output: JsonFast::OUTPUT_STRING);
$compact = JsonFast::minify($json, JsonFast::OUTPUT_STRING);

Native tools, weird experiments, and practical performance work.