dnonov/json-parser

Thin wrapper around `json_decode` and `json_encode` with exceptions and some handy methods.

v1.0.2 2024-09-02 20:35 UTC

This package is auto-updated.

Last update: 2024-11-03 19:39:10 UTC


README

Latest Version on Packagist GitHub Tests Action Status

About

Thin wrapper around json_decode and json_encode with exceptions and some handy methods.

Requirements

PHP 7.4^

Installation

You can install the package via composer:

composer require dnonov/json-parser

Description

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.

Here's how to use it

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);

Various exceptions might be thrown during decoding and encoding.

  • JsonMaxDepthException
  • JsonInvalidOrMalformedException
  • JsonControlCharacterException
  • JsonSyntaxErrorException
  • JsonMalformedUTF8Exception
  • JsonRecursiveReferenceException
  • JsonInfinityOrNanDetectedException
  • JsonUnsupportedTypeException
  • JsonException
  • InvalidArgumentExceptions

Here's documentation on the equivalent errors in PHP Doc

Contributing

Bug reports and pull requests are always welcome.

License

The MIT License (MIT). Please see License File for more information.