A package for handling JSON data, focusing on performance

1.0.2 2019-08-26 18:17 UTC


Release License Code Quality Build

What's it?

A component for your JSON data. Huh! Just that? No! Continue reading.

Why Json?


Note: Unfortunately, things are slow in the current version of Json (i.e. not only the lack of micro-optimizations, but the general performance is not good). It's recommended to wait for the next version (maybe 2.0.0) to use Json (if you don't care, then use it). See #59 for more details.

Thinking of performance? Json is here. Many methods have been tested to perform as fast as they could. Sometimes, they are faster than internals. Really? Test it yourself!


  • Json is not only for JSON data. So what? Many types are supported, including JSON strings, arrays, objects and scalars (+ null). Resources are not supported, and won't be supported (because of the standards).
  • Use methods regardless of the data type. Merging two objects? Actually.
  • Do anything, even if not provided by the class, using a callable. Alternatives? Extend from the class and define your own things. For sure, it will be easy in both cases.
  • Oh, what if an index does not exist? Exception. Parsing bad JSON data? Exception, again. Warnings and notices? Very rare cases.

Many Ways

Like JavaScript dots to get indexes, or native PHP arrays? Choose. Even with JavaScript-like indexes, you can pass the index to a method or you can use Json::index(). It is your decision.


An example from PHPUnit source code:

function prettify(string $json): string {
    $decodedJson = \json_decode($json, true);

    if (\json_last_error()) {
        throw new Exception(
            'Cannot prettify invalid json'

    return \json_encode($decodedJson, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES);

Looks good, but it can be really better:

// use MAChitgarha\Component\Json

function prettify(string $jsonStr): string {
    return Json::new($jsonStr)->getAsJson(\JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES);


  • Handling different exceptions is easier. Not just getting "Cannot prettify invalid json". Get exception message based on the error happened. Debugging will be easier.
  • Less code. Looks prettier. One line. Besides, sometimes, you don't even need to define that method, use Json directly without a function overhead.

Good! What Do I Need?

Almost nothing. PHP7, the JSON extension that comes with PHP7 by default, and usually Composer.


Composer is there!

composer require machitgarha/json

Note: You can also clone the project and load the files in your own way. The recommended way is Composer, however.


Note: The documentation is currently outdated. Use the code documentation. We try to update it as soon as possible.

See the GitHub wiki.


Excellent! Thank you! More details can be found here.