PHPackages                             xpat23/xpat-json-object - 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. xpat23/xpat-json-object

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

xpat23/xpat-json-object
=======================

Immutable object-oriented JSON manipulation library with clean dot notation API for PHP

v1.0.0(10mo ago)015MITPHPPHP ^8.1

Since Jul 12Pushed 10mo agoCompare

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

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

xpat-json-object
================

[](#xpat-json-object)

[![Latest Version](https://camo.githubusercontent.com/97dba04487307a9455fbb43c15c6af57ca8e959e789a813a1b8250ced2d7b33f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7870617432332f787061742d6a736f6e2d6f626a6563742e737667)](https://packagist.org/packages/xpat23/xpat-json-object)[![PHP Version](https://camo.githubusercontent.com/c18fb4a97f8ddbca1a8ab1b2cfcc718f5141232378db8266f099e7b2f4f45924/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f7870617432332f787061742d6a736f6e2d6f626a6563742e737667)](https://packagist.org/packages/xpat23/xpat-json-object)[![License](https://camo.githubusercontent.com/d53024177d6af5ea2b3609f070538ab104f69692bdd528d473f459854ff793c8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7870617432332f787061742d6a736f6e2d6f626a6563742e737667)](https://github.com/xpat23/xpat-json-object/blob/main/LICENSE)

A clean, immutable, object-oriented JSON manipulation library for PHP with intuitive dot notation API.

Why xpat-json-object?
---------------------

[](#why-xpat-json-object)

- **🔒 Immutable** - All operations return new instances, original data never changes
- **🎯 Dot notation** - Access nested data with simple `get('user.settings.theme')` syntax
- **⚡ Fluent API** - Chain operations naturally with `$json->set('key', 'value')->remove('old')`
- **🏗️ Object-oriented** - Clean OOP design, no global functions or static abuse
- **🛡️ Type safe** - Built for PHP 8.1+ with proper type declarations
- **📦 Zero dependencies** - Pure PHP, no external requirements

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

[](#installation)

```
composer require xpat23/xpat-json-object
```

Quick Start
-----------

[](#quick-start)

```
use Xpat\JsonObject\JsonObject;

// Create from array
$json = JsonObject::fromArray([
    'user' => [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'settings' => [
            'theme' => 'dark',
            'notifications' => true
        ]
    ]
]);

// Access nested data with dot notation
echo $json->get('user.name'); // "John Doe"
echo $json->get('user.settings.theme'); // "dark"

// Check if keys exist
if ($json->has('user.settings.notifications')) {
    echo 'User has notification settings';
}

// Immutable operations - returns new instances
$updated = $json
    ->set('user.age', 30)
    ->set('user.settings.language', 'en')
    ->remove('user.settings.notifications');

// Original unchanged, $updated is a new instance
echo $json->get('user.age'); // null (original unchanged)
echo $updated->get('user.age'); // 30 (new instance)
```

Features
--------

[](#features)

### Factory Methods

[](#factory-methods)

```
// From array
$json = JsonObject::fromArray(['key' => 'value']);

// From JSON string
$json = JsonObject::fromString('{"key": "value"}');

// From file
$json = JsonObject::fromFile('config.json');

// Empty object
$json = JsonObject::empty();
```

### Dot Notation Access

[](#dot-notation-access)

```
$json = JsonObject::fromArray([
    'app' => [
        'database' => [
            'host' => 'localhost',
            'port' => 3306
        ]
    ]
]);

// Get values
$host = $json->get('app.database.host'); // "localhost"
$port = $json->get('app.database.port', 5432); // 3306, with default fallback

// Check existence
$hasHost = $json->has('app.database.host'); // true
$hasPassword = $json->has('app.database.password'); // false
```

### Immutable Operations

[](#immutable-operations)

```
// All operations return new instances
$original = JsonObject::fromArray(['count' => 1]);

$incremented = $original->set('count', 2);
$withExtra = $incremented->set('extra', 'data');
$removed = $withExtra->remove('extra');

// Chain operations fluently
$result = JsonObject::empty()
    ->set('user.name', 'Jane')
    ->set('user.email', 'jane@example.com')
    ->set('user.active', true);
```

### Data Transformation

[](#data-transformation)

```
$numbers = JsonObject::fromArray(['a' => 1, 'b' => 2, 'c' => 3]);

// Filter
$evens = $numbers->filter(fn($value) => $value % 2 === 0);

// Map
$doubled = $numbers->map(fn($value) => $value * 2);

// Transform
$squared = $numbers->transform(fn($data) =>
    array_map(fn($v) => $v * $v, $data)
);
```

### Merging

[](#merging)

```
$config1 = JsonObject::fromArray([
    'database' => ['host' => 'localhost']
]);

$config2 = JsonObject::fromArray([
    'database' => ['port' => 3306, 'name' => 'myapp']
]);

// Deep merge
$merged = $config1->deepMerge($config2);
// Result: ['database' => ['host' => 'localhost', 'port' => 3306, 'name' => 'myapp']]
```

### Subsetting

[](#subsetting)

```
$user = JsonObject::fromArray([
    'id' => 1,
    'name' => 'John',
    'email' => 'john@example.com',
    'password' => 'secret',
    'settings' => ['theme' => 'dark']
]);

// Get only specific keys
$public = $user->only(['id', 'name', 'email']);

// Get all except specific keys
$safe = $user->except(['password']);
```

### Export Methods

[](#export-methods)

```
// To array
$array = $json->toArray();

// To JSON string
$jsonString = $json->toJson();

// Pretty JSON
$prettyJson = $json->toPrettyJson();

// Get all available keys
$keys = $json->keys(); // ['user.name', 'user.email', 'user.settings.theme']
```

### Utility Methods

[](#utility-methods)

```
// Count root level items
$count = $json->count();

// Check if empty
$isEmpty = $json->isEmpty();

// Get all dot notation keys
$allKeys = $json->keys();
```

Advanced Usage
--------------

[](#advanced-usage)

### Working with APIs

[](#working-with-apis)

```
// Parse API response
$response = JsonObject::fromString($apiResponse);

// Extract specific data
$userData = $response->only([
    'user.id',
    'user.name',
    'user.profile.avatar'
]);

// Transform for frontend
$frontendData = $userData
    ->set('user.displayName', $userData->get('user.name'))
    ->set('user.hasAvatar', $userData->has('user.profile.avatar'))
    ->remove('user.name');
```

### Configuration Management

[](#configuration-management)

```
// Load config files
$appConfig = JsonObject::fromFile('config/app.json');
$dbConfig = JsonObject::fromFile('config/database.json');

// Merge configurations
$config = $appConfig->deepMerge($dbConfig);

// Environment-specific overrides
if ($environment === 'production') {
    $config = $config->set('app.debug', false);
}
```

### Data Validation Pipeline

[](#data-validation-pipeline)

```
$data = JsonObject::fromArray($inputData);

// Validate and transform
$validated = $data
    ->filter(fn($value, $key) => !empty($value)) // Remove empty values
    ->set('created_at', date('Y-m-d H:i:s'))     // Add timestamp
    ->remove('_token');                          // Remove CSRF token

if (!$validated->has('email')) {
    throw new InvalidArgumentException('Email is required');
}
```

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

[](#requirements)

- PHP 8.1 or higher
- JSON extension (typically included with PHP)

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

Testing
-------

[](#testing)

```
# Run tests
composer test

# Run tests with coverage
composer test-coverage

# Run static analysis
composer phpstan

# Check code style
composer cs-check

# Fix code style
composer cs-fix

# Run all quality checks
composer quality
```

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Changelog
---------

[](#changelog)

### v1.0.0

[](#v100)

- Initial release
- Immutable JsonObject with dot notation support
- Factory methods for creating instances
- Fluent API for chaining operations
- Data transformation methods
- Merge and subset operations

Support
-------

[](#support)

- 📫 **Issues**: [GitHub Issues](https://github.com/xpat23/xpat-json-object/issues)
- 💬 **Discussions**: [GitHub Discussions](https://github.com/xpat23/xpat-json-object/discussions)
- 📖 **Documentation**: [GitHub Wiki](https://github.com/xpat23/xpat-json-object/wiki)

---

Made with ❤️ by [xpat](https://github.com/xpat23)

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance58

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

301d ago

### Community

Maintainers

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

---

Top Contributors

[![xpat23](https://avatars.githubusercontent.com/u/15974310?v=4)](https://github.com/xpat23 "xpat23 (1 commits)")

---

Tags

phpjsonobjectfluentimmutableOOPdot notation

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/xpat23-xpat-json-object/health.svg)

```
[![Health](https://phpackages.com/badges/xpat23-xpat-json-object/health.svg)](https://phpackages.com/packages/xpat23-xpat-json-object)
```

###  Alternatives

[adhocore/json-fixer

Fix/repair truncated JSON data

51543.2k2](/packages/adhocore-json-fixer)[blancks/fast-jsonpatch-php

Class designed to efficiently handle JSON Patch operations in accordance with the RFC 6902 specification

396.4k](/packages/blancks-fast-jsonpatch-php)[josantonius/json

PHP simple library for managing Json files.

1621.6k10](/packages/josantonius-json)

PHPackages © 2026

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