Thin wrapper around json_decode
and json_encode
with exceptions and some handy methods.
PHP 7.4^
You can install the package via composer:
composer require dnonov/json-parser
This mainly exists because of the silent json_decode
; if something's wrong it
will return null
. I prefer exceptions and nicer method names.
It is very thin wrapper around three functions in PHP standard library, but I'm
tired of re-writing it every time.
use Dnonov\JsonParser\Facades\JSONParser;
$arrayData = JSONParser::decodeToArray("[{"one": 1, "two": 2}]");
$objectData = JSONParser::decodeToObject("[{"one": 1, "two": 2}]");
$array = ["one" => 1, "two" => 2];
$encodedArrayData = JSONParser::encode($array);
// Make sure file path is relative to `base_path()`.
$arrayFileData = JSONParser::decodeFromFileToArray("./data.json");
$objectFileData = JSONParser::decodeFromFileToObject("./data.json");
// There are some handy methods.
$object = JSONParser::arrayToObject(["one" => 1, "two" => 2]);
$array = JSONParser::objectToArray($object);
- JsonMaxDepthException
- JsonInvalidOrMalformedException
- JsonControlCharacterException
- JsonSyntaxErrorException
- JsonMalformedUTF8Exception
- JsonRecursiveReferenceException
- JsonInfinityOrNanDetectedException
- JsonUnsupportedTypeException
- JsonException
- InvalidArgumentExceptions
Here's documentation on the equivalent errors in PHP Doc
Bug reports and pull requests are always welcome.
The MIT License (MIT). Please see License File for more information.