json is a fluent, object-oriented wrapper around PHP’s native JSON functions.
composer require rahulmac/json- PHP v8.0+
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();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(); // falseUse 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 missingTo 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'); // falseNote
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.
json is open-sourced software licensed under the MIT license.