Wrapper for PHP json functions

2.4.1 2019-10-14 02:20 UTC

This package is auto-updated.

Last update: 2022-05-17 05:30:00 UTC


Latest Version on Packagist Total Downloads Open Issues License

A simple wrapper for json_encode and json_decode with error handling

By Simon Hampel.

Note: as of PHP v7.3 there is now a JSON_THROW_ON_ERROR option for both native commands which should effectively render this package obsolete.


The recommended way of installing Hampel Json is through Composer:

    "require": {
        "hampel/json": "^2.0"

Note that there are three versions of this package, depending on the version of PHP you use:

  • v2.1 supports PHP >= v5.3.3
  • v2.2 supports PHP >= v5.4.0
  • v2.3 supports PHP >= v5.5.0

The three versions will be maintained in parallel


All parameters are the same as specified for the PHP functions json_encode and json_decode respectively.

The main difference that this class provides is that it throws exceptions when there are errors and translates the error codes into meaningful text for you automatically.


use Hampel\Json\Json;
use Hampel\Json\JsonException;

$data = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

// Encode a variable as JSON:
echo Json::encode($data);

// Encode options
echo Json::encode($data, $options);

// Decode JSON:

// Error handling
try {
    Json::decode('{"a":1,"b":2,"c":3,"d":4,"e":5'); // missing }
} catch (JsonException $e) {
    echo "Oops: " . $e->getMessage();