rahulmac/json

json is a fluent, object-oriented wrapper around PHP’s native JSON functions.

Installs: 23

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/rahulmac/json

v1.0.0 2026-02-08 10:02 UTC

This package is auto-updated.

Last update: 2026-02-08 10:04:24 UTC


README

Packagist Version GitHub License Tests

json

json is a fluent, object-oriented wrapper around PHP’s native JSON functions.

Installation

composer require rahulmac/json

Prerequisites

  • PHP v8.0+

Usage

Encoding JSON

Use Json::from() to encode PHP values into JSON.

use Rahulmac\Json\Json;

$json = Json::from(['foo' => 'bar'])->stringify();

To pretty-print:

$json = Json::from(['foo' => 'bar'])->prettify();

Using custom flags and depth:

$json = Json::from($data)
    ->withFlags(JSON_UNESCAPED_SLASHES)
    ->withDepth(256)
    ->stringify();

Decoding JSON

Use Json::of() to decode a JSON string.

use Rahulmac\Json\Json;

$value = Json::of('{"foo":"bar"}')->parse();

To decode as an array:

$array = Json::of('{"foo":"bar"}')->toArray();

To validate:

$isValid = Json::of('{"foo":"bar"}')->isValid(); // true
$isValid = Json::of('{invalid json}')->isValid(); // false

Accessors & Key-Existence

Use get() with dot notation to access nested values:

use Rahulmac\Json\Json;

$decoder = Json::of('{"user":{"id":123,"name":"Alice","active":true,"balance":99.5}}');

$id      = $decoder->get('user.id');          // 123
$name    = $decoder->get('user.name');      // "Alice"
$status  = $decoder->get('user.active');  // true
$unknown = $decoder->get('user.unknown', 'default'); // "default"

For type-safety, use can use type-safe helpers that fetch a value and cast it to the requested type:

$age     = $decoder->asInt('user.id');           // 123
$balance = $decoder->asFloat('user.balance');   // 99.5
$name    = $decoder->asString('user.name');     // "Alice"
$active  = $decoder->asBool('user.active');     // true

$roles   = $decoder->asArray('user.roles', []); // [] if missing

To determine if a key exists:

Json::of('{"foo":"bar"}')->has('foo'); // true
Json::of('{"foo":"bar"}')->has('baz'); // false
Json::of('{"foo":{"bar":"baz"}')->has('foo.bar'); // true
Json::of('{"foo":{"bar":"baz"}')->has('foo.baz'); // false

Note

While encoding/decoding use addFlags() to append flags and withFlags() to override them.

Warning

All encoding/decoding/accessor/key-existence methods throw \JsonException if an invalid JSON is received.

License

json is open-sourced software licensed under the MIT license.