arokettu/json

ext-json wrapper with sane defaults

2.1.0 2023-12-04 18:29 UTC

This package is auto-updated.

Last update: 2024-11-11 15:12:22 UTC


README

Packagist Packagist Gitlab pipeline status Codecov

A wrapper for the standard ext-json with sane defaults

Installation

composer require 'arokettu/json'

Features

Decoding wrapper

Decoding wrapper is the main purpose of the library. It's killer feature is that JSON objects become instances of ArrayObject instead of stdClass. This both keeps array/object types of the original and allows to work with all data as with arrays.

<?php

$obj = \Arokettu\Json\Json::decode('{"abc": 123}');

// we can access any data array-style
var_dump($obj['abc']);
// or object-style
var_dump($obj->abc);

// object will not turn into array
echo \Arokettu\Json\Json::encode($obj);

Options objects

OOP interface for json flags: EncodeOptions, DecodeOptions, ValidateOptions

<?php

use Arokettu\Json\EncodeOptions;

// set options with methods
$options = EncodeOptions::build()
    ->withThrowOnError()
    ->withHexAmp();
// set options with PHP 8 named params
$options = EncodeOptions::build(
    throw_on_error: true,   // apply JSON_THROW_ON_ERROR 
    hex_amp: true,          // apply JSON_HEX_AMP 
);
// use both with this library and with the base function
$value = \Arokettu\Json\Json::encode($json, $options);
$value = json_encode($json, $options->value()); 
// pretty print existing options mix
echo EncodeOptions::build(4194752)->toString();
// will get you 'JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT'

Documentation

Read full documentation here: https://sandfox.dev/php/json.html

Also on Read the Docs: https://arokettu-json.readthedocs.io/

Support

Please file issues on our main repo at GitLab: https://gitlab.com/sandfox/php-json/-/issues

License

The library is available as open source under the terms of the MIT License.