Laravel JSON – A Simple Wrapper Around JSON for Catching Errors


June 13th, 2018

Laravel JSON – A Simple Wrapper Around JSON for Catching Errors

When we wrote PHP 7.3: A Look at JSON Error Handling, Jan Östlund mentioned a package he wrote called Laravel JSON. Laravel JSON is a small package that makes encoding and decoding JSON a breeze with exceptions thrown on error immediately:

A simple wrapper around json_encode() and json_decode() for catching any errors without executing json_last_error().

Here’s the basic usage to encode JSON with this package:

use Eastwest\Json\Facades\Json;
$json = Json::encode(['key' => 'value]);
$array = Json::decode('{"key1":"value1","key2":"value2"}');
// Assoc = false
$array = Json::decode('{"key1":"value1","key2":"value2"}', false);

Returned objects are converted to an associative array by default.

The package immediately throws an exception when an error occurs, and you can catch them with EncodeDecode:

use Eastwest\Json\Exceptions\EncodeDecode;
try {
Json::decode('{bad json');
} catch (EncodeDecode $e) {
// Handle exception

Thank you, Jan, for this excellent package! Jan is also the author of F-Bar, an application for Mac OS and iOS, an app that enables you to manage your Laravel Forge servers on your Mac or your iPhone.

Learn More

You can check out Jan’s Laravel JSON package on GitHub for installation and usage instructions. I would also suggest reading our post on PHP 7.3: A Look at JSON Error Handling to learn how you can throw and handle JSON errors in PHP 7.3.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.