PHPackages                             philiprehberger/php-safe-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. philiprehberger/php-safe-json

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

philiprehberger/php-safe-json
=============================

Safe JSON parsing with exceptions, schema validation, and typed getters

v1.2.0(2mo ago)138MITPHPPHP ^8.2CI passing

Since Mar 13Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/php-safe-json)[ Packagist](https://packagist.org/packages/philiprehberger/php-safe-json)[ Docs](https://github.com/philiprehberger/php-safe-json)[ GitHub Sponsors](https://github.com/philiprehberger)[ RSS](/packages/philiprehberger-php-safe-json/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (6)Versions (6)Used By (0)

PHP Safe JSON
=============

[](#php-safe-json)

[![Tests](https://github.com/philiprehberger/php-safe-json/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/php-safe-json/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/93802467cde239b348eb0c81ebfd1a94058f048cecb3cc9adce139f5f6a0b25e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f7068702d736166652d6a736f6e2e737667)](https://packagist.org/packages/philiprehberger/php-safe-json)[![Last updated](https://camo.githubusercontent.com/cc7f37e5bb4a362a54c890cee66d94f38818d6586e2c337b926ab6d4c030d5f3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f7068702d736166652d6a736f6e)](https://github.com/philiprehberger/php-safe-json/commits/main)

Safe JSON parsing with exceptions, schema validation, and typed getters.

Requirements
------------

[](#requirements)

- PHP 8.2+

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

[](#installation)

```
composer require philiprehberger/php-safe-json
```

Usage
-----

[](#usage)

### Decoding JSON

[](#decoding-json)

```
use PhilipRehberger\SafeJson\SafeJson;

$obj = SafeJson::decode('{"name":"Alice","age":30,"active":true}');

$obj->string('name');   // "Alice"
$obj->int('age');       // 30
$obj->bool('active');   // true
```

### Dot Notation for Nested Access

[](#dot-notation-for-nested-access)

```
$obj = SafeJson::decode('{"user":{"address":{"city":"Vienna"}}}');

$obj->string('user.address.city'); // "Vienna"
$obj->has('user.address.city');    // true
$obj->has('user.address.zip');     // false
```

### Nested Objects

[](#nested-objects)

```
$obj = SafeJson::decode('{"user":{"name":"Alice"}}');

$user = $obj->object('user');
$user->string('name'); // "Alice"
```

### Safe Decoding (No Exceptions)

[](#safe-decoding-no-exceptions)

```
$obj = SafeJson::tryDecode('{invalid}');
// Returns null instead of throwing

$obj = SafeJson::tryDecode('{"valid":true}');
// Returns JsonObject
```

### Default Values

[](#default-values)

```
$obj = SafeJson::decode('{"name":"Alice"}');

$obj->get('name');              // "Alice"
$obj->get('missing', 'default'); // "default"
$obj->get('missing');           // throws JsonKeyException
```

### Nullable Accessors

[](#nullable-accessors)

```
$obj = SafeJson::decode('{"name":"Alice","age":30}');

$obj->stringOrNull('name');    // "Alice"
$obj->stringOrNull('missing'); // null
$obj->intOrNull('name');       // null (wrong type)
$obj->intOrNull('age');        // 30
```

### Merging Objects

[](#merging-objects)

```
$a = SafeJson::decode('{"name":"Alice","age":30}');
$b = SafeJson::decode('{"name":"Bob","email":"bob@example.com"}');

$merged = $a->merge($b);
$merged->string('name');  // "Bob" (overridden)
$merged->int('age');      // 30 (kept from $a)
$merged->string('email'); // "bob@example.com" (added from $b)
```

### JSON Path Querying

[](#json-path-querying)

```
$obj = SafeJson::decode('{"users":[{"name":"Alice","age":30},{"name":"Bob","age":25}]}');

$obj->query('$.users[*].name');       // ['Alice', 'Bob']
$obj->query('$.users[0].age');        // [30]
$obj->query('$..name');               // ['Alice', 'Bob'] (recursive descent)
$obj->query('$.users[0:1]');          // [['name' => 'Alice', 'age' => 30]]
```

Supported syntax: `$` (root), `.key` (child), `[0]` (index), `[*]` (wildcard), `..key` (recursive descent), `[0:3]` (slice), `['key']` (bracket notation).

### JSON Diffing

[](#json-diffing)

```
$changes = SafeJson::diff(
    '{"name":"Alice","age":30}',
    '{"name":"Bob","age":30,"email":"bob@example.com"}'
);

// [
//   ['op' => 'replace', 'path' => 'name', 'value' => 'Bob', 'old' => 'Alice'],
//   ['op' => 'add', 'path' => 'email', 'value' => 'bob@example.com'],
// ]
```

### Streaming Decode

[](#streaming-decode)

```
// Memory-efficient decoding of large JSON arrays
foreach (SafeJson::decodeStream('/path/to/large-file.json') as $element) {
    // Each element is decoded one at a time
    // Only one element is held in memory
}
```

### Encoding

[](#encoding)

```
$json = SafeJson::encode(['key' => 'value']);
// '{"key":"value"}'

$json = SafeJson::tryEncode($data);
// Returns null on failure instead of throwing
```

### Serialization

[](#serialization)

```
$obj = SafeJson::decode('{"key":"value"}');

$obj->toArray(); // ['key' => 'value']
$obj->toJson();  // '{"key":"value"}'
json_encode($obj); // '{"key":"value"}' (JsonSerializable)
(string) $obj;     // '{"key":"value"}' (Stringable)
```

API
---

[](#api)

### `SafeJson`

[](#safejson)

MethodDescription`decode(string $json): JsonObject`Decode JSON string, throws `JsonDecodeException` on failure`tryDecode(string $json): ?JsonObject`Decode JSON string, returns `null` on failure`encode(mixed $data, int $flags = 0): string`Encode to JSON string, throws on failure`tryEncode(mixed $data, int $flags = 0): ?string`Encode to JSON string, returns `null` on failure`diff(string $jsonA, string $jsonB): array`Compare two JSON strings and return differences`decodeStream(string $filePath): Generator`Stream-decode a JSON array file, yielding elements one at a time### `JsonObject`

[](#jsonobject)

MethodDescription`string(string $key): string`Get string value by key`int(string $key): int`Get integer value by key`float(string $key): float`Get float value by key (accepts integers)`bool(string $key): bool`Get boolean value by key`stringOrNull(string $key): ?string`Get string value or null if missing/wrong type`intOrNull(string $key): ?int`Get integer value or null if missing/wrong type`floatOrNull(string $key): ?float`Get float value or null if missing/wrong type`boolOrNull(string $key): ?bool`Get boolean value or null if missing/wrong type`array(string $key): array`Get array value by key`object(string $key): JsonObject`Get nested JsonObject by key`get(string $key, mixed $default = null): mixed`Get value without type enforcement`has(string $key): bool`Check if key exists`merge(self $other): self`Merge with another JsonObject (other overrides on conflict)`query(string $path): array`Query data using JSON Path expression`toArray(): array`Return underlying array`toJson(int $flags = 0): string`Return JSON stringAll key-based methods support dot notation for nested access (e.g., `user.address.city`).

### `JsonPath`

[](#jsonpath)

MethodDescription`query(array $data, string $path): array`Query data using JSON Path expression### `JsonDiff`

[](#jsondiff)

MethodDescription`diff(mixed $a, mixed $b, string $path = ''): array`Compare two values and return list of differences### `StreamDecoder`

[](#streamdecoder)

MethodDescription`decodeStream(string $filePath): Generator`Stream-decode a JSON array file element by element### Exceptions

[](#exceptions)

ExceptionThrown When`JsonDecodeException`Invalid JSON input`JsonEncodeException`Failed to encode data`JsonKeyException`Missing key or type mismatchDevelopment
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/php-safe-json)

🐛 [Report issues](https://github.com/philiprehberger/php-safe-json/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/php-safe-json/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance88

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 93.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~4 days

Total

5

Last Release

85d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (14 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

jsonsafeencodedecodeparsetyped

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-php-safe-json/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-php-safe-json/health.svg)](https://phpackages.com/packages/philiprehberger-php-safe-json)
```

###  Alternatives

[yethee/tiktoken

PHP version of tiktoken

1623.7M28](/packages/yethee-tiktoken)[kherge/json

Encodes, decodes, and validates JSON data.

60234.2k6](/packages/kherge-json)[gioni06/gpt3-tokenizer

PHP package for Byte Pair Encoding (BPE) used by GPT-3.

84572.5k10](/packages/gioni06-gpt3-tokenizer)[devium/toml

A PHP encoder/decoder for TOML compatible with 1.0.0 and 1.1.0

3978.4k19](/packages/devium-toml)[serafim/json5

JSON5 parser

231.0k](/packages/serafim-json5)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
