PHP code example of diamond-dove / simple-json

1. Go to this page and download the library: Download diamond-dove/simple-json library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

diamond-dove / simple-json example snippets


use DiamondDove\SimpleJson\SimpleJsonReader;

SimpleJsonReader::create('users.json')->get()
   ->each(function(array $user) {
        // process the row
    });

use DiamondDove\SimpleJson\SimpleJsonReader;

// $records is an instance of Illuminate\Support\LazyCollection
$records = SimpleJsonReader::create($pathToJson)->get();

$records->each(function(array $user) {
   // in the first pass $user will contain
   // ['email' => '[email protected]', 'first_name' => 'john']
});

SimpleJsonReader::create($pathToJson)->get()
->filter(function(array $user) {
return strlen($user['first_name']) > 5;
})
->each(function(array $user) {
// processing user
});

use DiamondDove\SimpleJson\SimpleJsonReader;

// From a string
SimpleJsonReader::createFromString('[{"name": "John"}, {"name": "Jane"}]')
    ->get()
    ->each(function (array $user) {
        // process the row
    });

// From an open stream resource (you keep ownership of the resource)
$stream = fopen('php://temp', 'r+b');
fwrite($stream, '[{"name": "John"}]');

SimpleJsonReader::createFromResource($stream)->get()->each(/* ... */);

fclose($stream);

use DiamondDove\SimpleJson\SimpleJsonWriter;

$writer = SimpleJsonWriter::create($pathToJson)
    ->push([
        [
            'first_name' => 'John',
            'last_name' => 'Doe',
        ],
        [
            'first_name' => 'Jane',
            'last_name' => 'Doe',
        ],
    ]);

SimpleJsonWriter::create($this->pathToJson)
                        ->push([
                            'name'  => 'Thomas',
                            'state' => 'Nigeria',
                            'age'   => 22,
                        ])
                        ->push([
                            'name'  => 'Luis',
                            'state' => 'Nigeria',
                            'age'   => 32,
                        ]);

use DiamondDove\SimpleJson\Json;

$json = '{"user": {"name": "Ana", "age": 30, "address": {"city": "Santo Domingo"}}}';

$city = Json::parse($json)->path('user.address.city')->string();   // 'Santo Domingo'
$age  = Json::parse($json)->path('user.age')->int();               // 30

// Exception-free
$accessor = Json::tryParse($maybeJson);   // null when the JSON is invalid

$user = Json::parse($json)->path('user');

$user->path('name')->string();          // strict: throws JsonTypeException on a type mismatch
$user->path('age')->int();              // strict int (rejects 30.0 and "30")
$user->path('nickname')->stringOr('—'); // lenient: returns the default when missing/mismatched
$user->path('nickname')->stringOrNull();// lenient: returns null when missing/mismatched
$user->path('age')->isPresent();        // true — distinguishes a present null from a missing key

use DiamondDove\SimpleJson\Json;

$result = Json::validate('{"email": "[email protected]", "age": 30}', [
    'email'     => ' ['nullable', 'array'],
]);

$result->passes();     // bool
$result->fails();      // bool
$result->errors();     // ['user.name' => ['The user.name field is 

use DiamondDove\SimpleJson\Json;
use DiamondDove\SimpleJson\Mapping\Attributes\ListOf;

enum Status: string {
    case Active = 'active';
    case Inactive = 'inactive';
}

final class Address {
    public function __construct(
        public readonly string $city,
        public readonly ?string $zip = null,
    ) {}
}

final class Tag {
    public function __construct(public readonly string $label) {}
}

final class User {
    public function __construct(
        public readonly string $name,
        public readonly int $age,
        public readonly ?Address $address = null,            // nested DTO
        public readonly Status $status = Status::Active,     // backed enum
        #[ListOf(Tag::class)] public readonly array $tags = [], // list of DTOs
    ) {}
}

$user = Json::map('{
    "name": "Ana", "age": 30,
    "address": {"city": "Santo Domingo"},
    "status": "active",
    "tags": [{"label": "vip"}, {"label": "beta"}]
}', User::class);

$user->address->city;   // 'Santo Domingo'
$user->status;          // Status::Active
$user->tags[0]->label;  // 'vip'

use DiamondDove\SimpleJson\SimpleJsonReader;

SimpleJsonReader::create('users.json')->get()
    ->map(fn (array $row) => Json::map($row, User::class))
    ->each(function (User $user) {
        // strongly-typed, one row at a time, low memory
    });

use DiamondDove\SimpleJson\Json;

$json = '{"store": {"book": [
    {"title": "A", "price": 8.95},
    {"title": "B", "price": 12.99}
]}}';

Json::query($json, '$..book[?(@.price < 10)].title');  // ['A']
Json::query($json, '$.store.book[*].title');           // ['A', 'B']
Json::query($json, '$..nonexistent');                  // []  (empty match)

use DiamondDove\SimpleJson\Json;

$schema = '{"type":"object","atchesSchema('{"age":-1}', $schema);   // false

$result = Json::validateSchema('{"age":-1}', $schema);
$result->passes();   // false
$result->errors();   // ['/age: Number must be greater than or equal to 0']

use DiamondDove\SimpleJson\Json;

Json::mapTo('["a", "b", "c"]', 'list<string>');                 // ['a', 'b', 'c']
Json::mapTo('{"name": "Ana", "age": 30}', 'array{name: string, age: int}');
Json::mapTo('200', 'int<0, 100>');   // throws JsonMappingException (out of range)