PHP 7.3: Option to make json_encode and json_decode throw exceptions on errors

Version7.3
TypeNew Feature

This is one of my favorites. For all these years, json_encode() and json_decode() functions were silent about errors in the provided PHP variables or the JSON string. This was prone to buggy code because not everyone knows this edge case. This was even criticized in the famous PHP: A Fractal bad design post.

json_decode returns null for invalid input, even though null is also a perfectly valid object for JSON to decode to—this function is completely unreliable unless you also call json_last_error every time you use it.

It took us 6 years since that blog post, but we now have an option to make PHP throw an error on JSON operation failures:

try {
    json_decode("{", false, 512, JSON_THROW_ON_ERROR); 
}
catch (\JsonException $exception) {
    echo $exception->getMessage(); // echoes "Syntax error" 
}

The new \JsonException is a subclass of \Exception, and both JSON_THROW_ON_ERROR constant and JsonException exception are declared in the global namespace.

I highly recommend you start to use this feature. There are contributed libraries, such as daverandom/exceptional-json that brought similar functionality until PHP 7.2. With this feature now in PHP core, you can remove this package or tons of ugly boilerplate code calling json_last_error() every-time you make a JSON operation.

Backwards compatibility impact

None, unless you have declared your own exception and/or constants with conflicting names.

RFC Externals.io discussion Implementation