PHPackages                             technically/json - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. technically/json

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

technically/json
================

Minimalistic wrapper around PHP native JSON functions, with additional data validity and error checks.

1.0.1(4y ago)119MITPHPPHP ~7.3 || ~8.0CI passing

Since Aug 4Pushed 7mo agoCompare

[ Source](https://github.com/technically-php/json)[ Packagist](https://packagist.org/packages/technically/json)[ RSS](/packages/technically-json/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (4)Used By (0)

Technically JSON
================

[](#technically-json)

`Technically\Json` is a minimalistic wrapper around PHP native `json_encode` and `json_decode` functions, which always throws an exception in case of an error.

[![Tests Status](https://github.com/technically-php/json/actions/workflows/test.yml/badge.svg)](https://github.com/technically-php/json/actions/workflows/test.yml/badge.svg)

Features
--------

[](#features)

- PHP 7.3+
- PHP 8.0
- Semver
- Tests

Problem
-------

[](#problem)

Look, if an error occurs with `json_decode()`, by default, it sets the global error state that can be retrieved with `json_last_error()` and `json_last_error_msg()`. Alternatively, developers can use `JSON_THROW_ON_ERROR` option to make `json_decode()` throw an exception in case of invalid input.

Proper way of using the native `json_decode()` function, though many developers forget about it:

```
try {
    $data = json_decode($input, false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
    // handle invalid input
}
```

Or this:

```
$data = \json_decode($input);
$error = \json_last_error();

if ($error !== JSON_ERROR_NONE) {
    throw new \JsonException(\json_last_error_msg(), $error);
}
```

I believe it should be the default behavior of `json_decode()` and `json_encode()` to throw on errors. We don't have to remember about it.

Solution
--------

[](#solution)

```
use function Technically\Json\json_decode;

try {
    $data = json_decode($input);
} catch (JsonException $exception) {
    // handle invalid input
}
```

Installation
------------

[](#installation)

Use [Composer](https://getcomposer.org/) package manager to add the library to your project:

```
composer require technically/json

```

Usage
-----

[](#usage)

The namespaced `json_encode()` and `json_decode()` functions do always add `JSON_THROW_ON_ERROR` flag, but in the rest they work identically to the native functions: same arguments, same options, same result.

```
