|
| 1 | +# JSONParser |
| 2 | +## About |
| 3 | +Thin wrapper around `json_decode` and `json_encode` with exceptions and some handy methods. |
| 4 | + |
| 5 | +## Requirements |
| 6 | +PHP 7.4^ |
| 7 | + |
| 8 | +## Installation |
| 9 | + |
| 10 | +You can install the package via composer: |
| 11 | + |
| 12 | +```bash |
| 13 | +composer require dnonov/json-parser |
| 14 | +``` |
| 15 | + |
| 16 | +## Description |
| 17 | +This mainly exists because of the silent `json_decode`; if something's wrong it |
| 18 | +will return `null`. I prefer exception. I prefer nice method names as well. |
| 19 | +It is very thin wrapper around three functions in PHP standard library, but I'm |
| 20 | +tired of re-writing it every time. |
| 21 | + |
| 22 | +### Here's how to use it |
| 23 | +```php |
| 24 | +use Dnonov\JsonParser\Facades\JSONParser; |
| 25 | + |
| 26 | +$arrayData = JSONParser::decodeToArray("[{"one": 1, "two": 2}]"); |
| 27 | +$objectData = JSONParser::decodeToObject("[{"one": 1, "two": 2}]"); |
| 28 | + |
| 29 | +$array = ["one" => 1, "two" => 2]; |
| 30 | +$encodedArrayData = JSONParser::encode($array); |
| 31 | + |
| 32 | +// Make sure file path is relative to `base_path()`. |
| 33 | +$arrayFileData = JSONParser::decodeFromFileToArray("./data.json"); |
| 34 | +$objectFileData = JSONParser::decodeFromFileToObject("./data.json"); |
| 35 | + |
| 36 | +// There are some handy methods. |
| 37 | +$object = JSONParser::arrayToObject(["one" => 1, "two" => 2]); |
| 38 | +$array = JSONParser::objectToArray($object); |
| 39 | +``` |
| 40 | + |
| 41 | +### Various exceptions might be thrown during decoding and encoding. |
| 42 | +* JsonMaxDepthException |
| 43 | +* JsonInvalidOrMalformedException |
| 44 | +* JsonControlCharacterException |
| 45 | +* JsonSyntaxErrorException |
| 46 | +* JsonMalformedUTF8Exception |
| 47 | +* JsonRecursiveReferenceException |
| 48 | +* JsonInfinityOrNanDetectedException |
| 49 | +* JsonUnsupportedTypeException |
| 50 | +* JsonException |
| 51 | +* InvalidArgumentExceptions |
| 52 | + |
| 53 | +Here's documentation on the equivalent errors in [PHP Doc](https://www.php.net/manual/en/json.constants.php#constant.json-throw-on-error) |
| 54 | + |
| 55 | +## Contributing |
| 56 | +Bug reports and pull requests are always welcome. |
| 57 | + |
| 58 | +## License |
| 59 | +The MIT License (MIT). Please see [License File](LICENSE) for more information. |
0 commit comments