Laravel JSON – A Simple Wrapper Around JSON for Catching Errors

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: Laravel Packages / JSON
Laravel News Partners

Laravel Jobs

Senior Full-Stack Developer
Atlanta, GA - (remote) USA ONLY
PHP Laravel Developer
Looking for Senior Full-stack Laravel/React.js Javascript API Developer - Immediate (Full-time)
ApproveMe // Document Signing
Wordpress and/or Laravel Developer
Remote (Lexington, KY)
Mediocre Creative
Software Developer
Huntsville, AL


Join 31,000+ others and never miss out on new tips, tutorials, and more.