Skip to content

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

License

Notifications You must be signed in to change notification settings

DNonov/JSONParser

Repository files navigation

JSONParser

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.

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages