PHPackages                             jsonx/jsonx - 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. jsonx/jsonx

Abandoned → [webfiori/jsonx](/?search=webfiori%2Fjsonx)Library[Parsing &amp; Serialization](/categories/parsing)

jsonx/jsonx
===========

PHP library for creating JSON.

4.0.2(3w ago)8344[1 PRs](https://github.com/WebFiori/json/pulls)MITPHPPHP &gt;=8.1CI passing

Since Apr 15Pushed 1w ago1 watchersCompare

[ Source](https://github.com/WebFiori/json)[ Packagist](https://packagist.org/packages/jsonx/jsonx)[ Fund](https://paypal.me/IbrahimBinAlshikh)[ RSS](/packages/jsonx-jsonx/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (10)Dependencies (4)Versions (36)Used By (0)

WebFiori Json
=============

[](#webfiori-json)

A PHP library for creating and parsing JSON and JSONx strings. Supports all PHP scalar types, arrays, and objects with flexible property naming styles.

 [ ![](https://github.com/WebFiori/json/actions/workflows/php84.yaml/badge.svg?branch=main) ](https://github.com/WebFiori/json/actions/workflows/php84.yaml) [ ![](https://camo.githubusercontent.com/9d6a047c803ef4debe667a7beefddd00c52a8fceb69c45ca4bfe7ae094c42969/68747470733a2f2f636f6465636f762e696f2f67682f57656246696f72692f6a736f6e2f6272616e63682f6d61696e2f67726170682f62616467652e737667) ](https://codecov.io/gh/WebFiori/json) [ ![](https://camo.githubusercontent.com/ad2ae3f5e80b13a6667df4ec0a0b34e0c9482f8153f308753448b87439d54122/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d57656246696f72695f6a736f6e266d65747269633d616c6572745f737461747573) ](https://sonarcloud.io/dashboard?id=WebFiori_json) [ ![](https://camo.githubusercontent.com/ebc8ed2cad33f561d337079f65e489efbc734619b02eeac4c65f4629d0aa02b2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f57656246696f72692f6a736f6e2e7376673f6c6162656c3d6c6174657374) ](https://github.com/WebFiori/json/releases) [ ![](https://camo.githubusercontent.com/2e9d685842e49769d9717dcfc2779b9fc40e954ba4f09bebb0ebde057c1b13b5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f77656266696f72692f6a736f6e783f636f6c6f723d6c696768742d677265656e) ](https://packagist.org/packages/webfiori/jsonx) [![PHP 8.1+](https://camo.githubusercontent.com/6518db1335bf20fdff07253dc6d6d0cec955b5fb6a8ef1382ac6d73687ecc07f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d626c7565)](https://camo.githubusercontent.com/6518db1335bf20fdff07253dc6d6d0cec955b5fb6a8ef1382ac6d73687ecc07f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d626c7565)

Table of Contents
-----------------

[](#table-of-contents)

- [Key Features](#key-features)
- [Supported PHP Versions](#supported-php-versions)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage](#usage)
    - [Working With Arrays](#working-with-arrays)
    - [Working With Objects](#working-with-objects)
    - [Property Naming Styles](#property-naming-styles)
    - [Decoding JSON](#decoding-json)
    - [Typed Deserialization](#typed-deserialization)
    - [Saving to File](#saving-to-file)
    - [JSONx](#jsonx)
- [Error Handling](#error-handling)
- [API Reference](#api-reference)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)
- [Changelog](#changelog)

Key Features
------------

[](#key-features)

- Create well-formatted JSON strings from any PHP value (scalars, arrays, objects)
- Decode JSON strings and files into `Json` objects
- Typed deserialization via `Json::decodeAs()` with nested object hydration
- Flexible property naming styles: `camelCase`, `kebab-case`, `snake_case`, or `none`
- Letter case control: `same`, `upper`, `lower`
- Custom object serialization via the `JsonI` interface
- Auto-mapping of plain objects via public getter methods and public properties
- Auto-detection of associative arrays as JSON objects
- Attribute-based control: `#[JsonProperty]`, `#[JsonIgnore]`, `#[JsonType]`
- Application-wide defaults via `Json::setDefaults()`
- [JSONx](https://www.ibm.com/docs/en/datapower-gateways/10.0.1?topic=20-jsonx) output (XML representation of JSON)
- Save JSON output directly to a file

Supported PHP Versions
----------------------

[](#supported-php-versions)

Build Status[![](https://github.com/WebFiori/json/actions/workflows/php81.yaml/badge.svg?branch=main)](https://github.com/WebFiori/json/actions/workflows/php81.yaml)[![](https://github.com/WebFiori/json/actions/workflows/php82.yaml/badge.svg?branch=main)](https://github.com/WebFiori/json/actions/workflows/php82.yaml)[![](https://github.com/WebFiori/json/actions/workflows/php83.yaml/badge.svg?branch=main)](https://github.com/WebFiori/json/actions/workflows/php83.yaml)[![](https://github.com/WebFiori/json/actions/workflows/php84.yaml/badge.svg?branch=main)](https://github.com/WebFiori/json/actions/workflows/php84.yaml)Installation
------------

[](#installation)

```
composer require webfiori/jsonx
```

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

[](#quick-start)

```
use WebFiori\Json\Json;

$json = new Json([
    'name'    => 'Ibrahim',
    'age'     => 30,
    'married' => false,
    'score'   => 9.5,
    'notes'   => null,
]);

echo $json;
```

Output:

```
{"name":"Ibrahim","age":30,"married":false,"score":9.5,"notes":null}
```

You can also build the object incrementally:

```
$json = new Json();
$json->addString('name', 'Ibrahim');
$json->addNumber('age', 30);
$json->addBoolean('married', false);
$json->addNull('notes');
```

Usage
-----

[](#usage)

### Working With Arrays

[](#working-with-arrays)

```
$json = new Json();

// Indexed array
$json->addArray('tags', ['php', 'json', 'api']);

// Associative arrays are automatically encoded as JSON objects
$json->addArray('address', ['city' => 'Riyadh', 'country' => 'SA']);

echo $json;
```

Output:

```
{"tags":["php","json","api"],"address":{"city":"Riyadh","country":"SA"}}
```

### Working With Objects

[](#working-with-objects)

#### Using JsonI Interface

[](#using-jsoni-interface)

Implement `JsonI` to fully control how an object is serialized:

```
use WebFiori\Json\Json;
use WebFiori\Json\JsonI;

class User implements JsonI {
    public function __construct(
        private string $username,
        private string $email
    ) {}

    public function toJSON(): Json {
        return new Json(['username' => $this->username, 'email' => $this->email]);
    }
}

$json = new Json();
$json->addObject('user', new User('ibrahim', 'ibrahim@example.com'));
echo $json;
```

Output:

```
{"user":{"username":"ibrahim","email":"ibrahim@example.com"}}
```

#### Auto-Mapping Objects

[](#auto-mapping-objects)

Objects that don't implement `JsonI` are mapped automatically using:

1. **Public getter methods** — any zero-parameter method prefixed with `get` is called. The property name is derived by stripping `get` (e.g. `getName()` → `Name` with style `none`, or `name` with style `camel`).
2. **Public properties** — extracted via reflection and added as-is.

Use `#[JsonIgnore]` to exclude specific getters or properties, and `#[JsonProperty]` to override the output name:

```
use WebFiori\Json\Json;
use WebFiori\Json\JsonIgnore;
use WebFiori\Json\JsonProperty;

class Product {
    #[JsonProperty('product_sku')]
    public string $sku = 'ABC-001';

    #[JsonIgnore]
    public string $internalCode = 'X-99';

    private string $name;
    private float $price;

    public function __construct(string $name, float $price) {
        $this->name  = $name;
        $this->price = $price;
    }

    public function getName(): string { return $this->name; }
    public function getPrice(): float { return $this->price; }

    #[JsonProperty('on_sale')]
    public function getAvailable(): bool { return true; }

    #[JsonIgnore]
    public function getSecretMargin(): float { return 0.42; }
}

$json = new Json([], 'snake');
$json->addObject('product', new Product('Keyboard', 49.99));
echo $json;
```

Output:

```
{"product":{"name":"Keyboard","price":49.99,"on_sale":true,"product_sku":"ABC-001"}}
```

### Property Naming Styles

[](#property-naming-styles)

Four naming styles are supported: `none` (default), `camel`, `snake`, `kebab`.
Three letter cases are supported: `same` (default), `upper`, `lower`.

```
$data = ['first-name' => 'Ibrahim', 'last-name' => 'Al-Shikh'];

echo new Json($data, 'none')  . "\n"; // {"first-name":"Ibrahim","last-name":"Al-Shikh"}
echo new Json($data, 'camel') . "\n"; // {"firstName":"Ibrahim","lastName":"Al-Shikh"}
echo new Json($data, 'snake') . "\n"; // {"first_name":"Ibrahim","last_name":"Al-Shikh"}
echo new Json($data, 'kebab') . "\n"; // {"first-name":"Ibrahim","last-name":"Al-Shikh"}
```

Set application-wide defaults:

```
Json::setDefaults(style: 'camel', case: 'lower', formatted: false);
```

### Decoding JSON

[](#decoding-json)

Decode a JSON string:

```
$json = Json::decode('{"name":"Ibrahim","age":30}');
echo $json->get('name'); // Ibrahim
```

Read from a file:

```
$json = Json::fromJsonFile('/path/to/file.json');
```

### Typed Deserialization

[](#typed-deserialization)

Deserialize JSON directly into typed objects:

```
class User {
    public function __construct(
        private string $username,
        private string $email
    ) {}
    public function getUsername(): string { return $this->username; }
    public function getEmail(): string { return $this->email; }
}

$user = Json::decodeAs('{"username":"ibrahim","email":"a@b.com"}', User::class);
echo $user->getUsername(); // ibrahim
```

Nested objects are resolved automatically via constructor type hints. Use `#[JsonType]` for arrays of objects:

```
use WebFiori\Json\JsonType;

class Order {
    public function __construct(
        private User $customer,
        #[JsonType(LineItem::class, isArray: true)]
        private array $items
    ) {}
}

$order = Json::decodeAs($jsonString, Order::class);
$order->getCustomer();  // User instance
$order->getItems();     // LineItem[] array
```

Runtime type mapping without attributes:

```
$json = Json::decode($jsonString);
$json->setTypeMap([
    'customer' => User::class,
    'items'    => [LineItem::class],
]);
$json->get('customer'); // User instance
$json->get('items');    // LineItem[] array
```

### Saving to File

[](#saving-to-file)

```
$json = new Json(['name' => 'Ibrahim', 'age' => 30]);
$json->toJsonFile('data', '/path/to/directory', true);
// Creates /path/to/directory/data.json
```

### JSONx

[](#jsonx)

[JSONx](https://www.ibm.com/docs/en/datapower-gateways/10.0.1?topic=20-jsonx) is an IBM standard that represents JSON as XML:

```
$json = new Json(['name' => 'Ibrahim', 'age' => 30, 'isEmployed' => true]);
echo $json->toJSONxString();
```

Output:

```

    Ibrahim
    30
    true

```

Error Handling
--------------

[](#error-handling)

All errors throw `\WebFiori\Json\JsonException`:

```
try {
    $json = Json::decode('{invalid json}');
} catch (\WebFiori\Json\JsonException $e) {
    echo $e->getMessage();
}
```

API Reference
-------------

[](#api-reference)

### Classes

[](#classes)

ClassDescription`Json`Main class for building, reading, and deserializing JSON data`JsonI`Interface for custom object serialization`JsonConverter`Handles serialization to JSON and JSONx strings`JsonDeserializer`Handles typed deserialization of JSON into objects`Property`Represents a single JSON property`CaseConverter`Converts property names between naming styles`JsonTypes`Constants for JSON data types`JsonException`Exception thrown on JSON errors### Attributes

[](#attributes)

AttributeTargetDescription`#[JsonIgnore]`Method, PropertyExclude from serialization`#[JsonProperty(name)]`Method, PropertyOverride output name`#[JsonType(class, isArray)]`Parameter, PropertySpecify type for deserialization### Key Methods — `Json`

[](#key-methods--json)

MethodDescription`add(string $key, mixed $value, bool $arrayAsObj = false): bool`Add any value`addString(string $key, string $val): bool`Add a string`addNumber(string $key, int|float $value): bool`Add a number`addBoolean(string $key, bool $val = true): bool`Add a boolean`addNull(string $key): bool`Add a null value`addArray(string $key, array $value, bool $asObject = false): bool`Add an array`addObject(string $key, object &$val): bool`Add an object`get(string $key): mixed`Get a property value`hasKey(string $key): bool`Check if a key exists`remove(string $key): ?Property`Remove a property`setPropsStyle(string $style, string $lettersCase = 'same'): void`Change naming style`setIsFormatted(bool $bool): void`Toggle formatted output`setTypeMap(array $map): void`Set type map for typed deserialization via get()`toJSONString(): string`Get JSON string`toJSONxString(): string`Get JSONx string`toJsonFile(string $fileName, string $path, bool $override = false): void`Save to file`Json::decode(string $jsonStr): Json`Decode a JSON string`Json::decodeAs(string $jsonStr, string $className): object`Decode and hydrate a typed object`Json::fromJsonFile(string $path): Json`Load from a JSON file`Json::setDefaults(?string $style, ?string $case, ?bool $formatted): void`Set application-wide defaults`Json::resetDefaults(): void`Reset to library defaultsTesting
-------

[](#testing)

```
# Install dependencies
composer install

# Run tests
composer test
```

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

[](#contributing)

Contributions are welcome! Please open an issue or submit a pull request on [GitHub](https://github.com/WebFiori/json).

License
-------

[](#license)

This library is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.

Support
-------

[](#support)

If you encounter any issues, please [open an issue](https://github.com/WebFiori/json/issues) on GitHub.

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for a list of changes.

###  Health Score

55

—

FairBetter than 97% of packages

Maintenance97

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

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

Recently: every ~124 days

Total

27

Last Release

19d ago

Major Versions

v1.4.8 → v2.0.02020-09-02

v2.1.0 → v3.0.02021-12-27

3.3.2 → 4.0.02025-08-03

4.0.2 → v5.0.0.x-dev2026-06-10

PHP version history (4 changes)v1.4.3PHP &gt;=5.6

v3.1.1PHP &gt;=7.0

4.0.0PHP &gt;=8.0

4.0.1PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/4c25e43acaa22b4fb758a710b69c2ab75947a6642925e3bec9c98196b1f2a433?d=identicon)[usernane](/maintainers/usernane)

---

Top Contributors

[![usernane](https://avatars.githubusercontent.com/u/12120015?v=4)](https://github.com/usernane "usernane (422 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (6 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![ibeladi-mrsool](https://avatars.githubusercontent.com/u/11488356?v=4)](https://github.com/ibeladi-mrsool "ibeladi-mrsool (1 commits)")

---

Tags

apishacktoberfestjsonjson-parserphpphp-librarywebfiori-frameworkphpjsonjsonx

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/jsonx-jsonx/health.svg)

```
[![Health](https://phpackages.com/badges/jsonx-jsonx/health.svg)](https://phpackages.com/packages/jsonx-jsonx)
```

###  Alternatives

[adhocore/json-fixer

Fix/repair truncated JSON data

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

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

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

PHP simple library for managing Json files.

1722.4k10](/packages/josantonius-json)

PHPackages © 2026

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