Encode, decode, handle errors and valid json with php

v1.0.0 2016-08-23 13:29 UTC

This package is not auto-updated.

Last update: 2024-10-25 23:36:00 UTC


README

Build Status Scrutinizer Code Quality Code Coverage License SensioLabsInsight

Why?

Mainly to handle errors json encode/decode and encapsulate options to encode easily.

Usage

use BernardoSecades\Json\Json;

...

Json::decode($value);
Json::encode($value);

Options in json encode:

use BernardoSecades\Json\Json;
use BernardoSecades\Json\Option;
use BernardoSecades\Json\ArrayOption;

...

$options = new ArrayOption();
$options[] = Option::JSON_UNESCAPED_UNICODE(); // Use enum object
$options[] = Option::JSON_UNESCAPED_SLASHES();
$options[] = Option::JSON_NUMERIC_CHECK();

Json::encode($value, $options);

Handle errors

use BernardoSecades\Json\Json;
use BernardoSecades\Json\DecodeException;
use BernardoSecades\Json\EncodeException;

...

try {
    Json::decode($value);
} catch (DecodeException $exception) {
    // do something
}

// or

if (!Json::isValid($value)) {
   // do something
}

try {
    Json::encode($value);
} catch (EncodeException $exception) {
 // do something
}

Get info from Encode/Decode exception

use BernardoSecades\Json\Json;
use BernardoSecades\Json\DecodeException;

...

try {
    Json::decode($value);
} catch (DecodeException $exception) {

    $errorMessage = sprintf('%s , json error code %d', 
        $exception->getMessage(), // see http://php.net/manual/en/function.json-last-error-msg.php
        $exception->getCode(),    // see http://php.net/manual/en/json.constants.php
    ); 

    $this->logger->error($errorMessage);
    // do something more
}

Installation

composer require bernardosecades/php-json