PHP code example of webfiori / jsonx

1. Go to this page and download the library: Download webfiori/jsonx 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/ */

    

webfiori / jsonx example snippets


use WebFiori\Json\Json;

$json = new Json([
    'name'    => 'Ibrahim',
    'age'     => 30,
    'married' => false,
    'score'   => 9.5,
    'notes'   => null,
]);

echo $json;

$json = new Json();
$json->addString('name', 'Ibrahim');
$json->addNumber('age', 30);
$json->addBoolean('married', false);
$json->addNull('notes');

$json = new Json();

// Indexed array
$json->addArray('tags', ['php', 'json', 'api']);

// Associative arrays are automatically encoded as JSON objects
$json->addArray('address', ['city' => 'Riyadh', 'country' => 'SA']);

echo $json;

use WebFiori\Json\Json;
use WebFiori\Json\JsonI;

class User implements JsonI {
    public function __construct(
        private string $username,
        private string $email
    ) {}

    public function toJSON(): Json {
        return new Json(['username' => $this->username, 'email' => $this->email]);
    }
}

$json = new Json();
$json->addObject('user', new User('ibrahim', '[email protected]'));
echo $json;

use WebFiori\Json\Json;
use WebFiori\Json\JsonIgnore;
use WebFiori\Json\JsonProperty;

class Product {
    #[JsonProperty('product_sku')]
    public string $sku = 'ABC-001';

    #[JsonIgnore]
    public string $internalCode = 'X-99';

    private string $name;
    private float $price;

    public function __construct(string $name, float $price) {
        $this->name  = $name;
        $this->price = $price;
    }

    public function getName(): string { return $this->name; }
    public function getPrice(): float { return $this->price; }

    #[JsonProperty('on_sale')]
    public function getAvailable(): bool { return true; }

    #[JsonIgnore]
    public function getSecretMargin(): float { return 0.42; }
}

$json = new Json([], 'snake');
$json->addObject('product', new Product('Keyboard', 49.99));
echo $json;

$data = ['first-name' => 'Ibrahim', 'last-name' => 'Al-Shikh'];

echo new Json($data, 'none')  . "\n"; // {"first-name":"Ibrahim","last-name":"Al-Shikh"}
echo new Json($data, 'camel') . "\n"; // {"firstName":"Ibrahim","lastName":"Al-Shikh"}
echo new Json($data, 'snake') . "\n"; // {"first_name":"Ibrahim","last_name":"Al-Shikh"}
echo new Json($data, 'kebab') . "\n"; // {"first-name":"Ibrahim","last-name":"Al-Shikh"}

Json::setDefaults(style: 'camel', case: 'lower', formatted: false);

$json = Json::decode('{"name":"Ibrahim","age":30}');
echo $json->get('name'); // Ibrahim

$json = Json::fromJsonFile('/path/to/file.json');

class User {
    public function __construct(
        private string $username,
        private string $email
    ) {}
    public function getUsername(): string { return $this->username; }
    public function getEmail(): string { return $this->email; }
}

$user = Json::decodeAs('{"username":"ibrahim","email":"[email protected]"}', User::class);
echo $user->getUsername(); // ibrahim

use WebFiori\Json\JsonType;

class Order {
    public function __construct(
        private User $customer,
        #[JsonType(LineItem::class, isArray: true)]
        private array $items
    ) {}
}

$order = Json::decodeAs($jsonString, Order::class);
$order->getCustomer();  // User instance
$order->getItems();     // LineItem[] array

$json = Json::decode($jsonString);
$json->setTypeMap([
    'customer' => User::class,
    'items'    => [LineItem::class],
]);
$json->get('customer'); // User instance
$json->get('items');    // LineItem[] array

$json = new Json(['name' => 'Ibrahim', 'age' => 30]);
$json->toJsonFile('data', '/path/to/directory', true);
// Creates /path/to/directory/data.json

$json = new Json([
    'name' => 'Ibrahim',
    'age' => 30,
    'active' => true,
]);

$address = new Json(['city' => 'Riyadh', 'country' => 'SA']);
$json->add('address', $address);

$array = $json->toArray();
// Result:
// [
//     'name' => 'Ibrahim',
//     'age' => 30,
//     'active' => true,
//     'address' => [
//         'city' => 'Riyadh',
//         'country' => 'SA',
//     ],
// ]

$json = new Json(['name' => 'Ibrahim', 'age' => 30, 'isEmployed' => true]);
echo $json->toJSONxString();

try {
    $json = Json::decode('{invalid json}');
} catch (\WebFiori\Json\JsonException $e) {
    echo $e->getMessage();
}
json
{"tags":["php","json","api"],"address":{"city":"Riyadh","country":"SA"}}