PHPackages                             xp-forge/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. xp-forge/json

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

xp-forge/json
=============

Reads and writes JSON to and from various input sources

v6.0.1(9mo ago)3223.0k↓18.6%112BSD-3-ClausePHPPHP &gt;=7.4.0CI passing

Since Dec 31Pushed 8mo ago3 watchersCompare

[ Source](https://github.com/xp-forge/json)[ Packagist](https://packagist.org/packages/xp-forge/json)[ Docs](http://xp-framework.net/)[ RSS](/packages/xp-forge-json/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (30)Used By (12)

JSON
====

[](#json)

[![Build status on GitHub](https://github.com/xp-forge/json/workflows/Tests/badge.svg)](https://github.com/xp-forge/json/actions)[![XP Framework Mdodule](https://raw.githubusercontent.com/xp-framework/web/master/static/xp-framework-badge.png)](https://github.com/xp-framework/core)[![BSD Licence](https://raw.githubusercontent.com/xp-framework/web/master/static/licence-bsd.png)](https://github.com/xp-framework/core/blob/master/LICENCE.md)[![Requires PHP 7.4+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-7_4plus.svg)](http://php.net/)[![Supports PHP 8.0+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-8_0plus.svg)](http://php.net/)[![Latest Stable Version](https://camo.githubusercontent.com/fe919df31886ecff7bcd6b5abd2d399c569e8307ef8c1ea472cf5e0d412f3c15/68747470733a2f2f706f7365722e707567782e6f72672f78702d666f7267652f6a736f6e2f76657273696f6e2e737667)](https://packagist.org/packages/xp-forge/json)

Reads and writes JSON to and from various input sources.

Examples
--------

[](#examples)

Reading can be done from a string, file or stream:

```
use text\json\Json;
use io\File;
use peer\SocketInputStream;

// Strings
$value= Json::read('"Test"');

// Input
$in= '{"Hello": "World"}');
$in= new File('input.json');
$in= new SocketInputStream(/* ... */);

$value= Json::read($in);
```

Writing can be done to a string, file or stream:

```
use text\json\Json;
use io\File;
use peer\SocketOutputStream;

// Strings
$json= Json::of('Test');

// Output
$out= new File('output.json');
$out= new SocketOuputStream(/* ... */);

Json::write($value, $out);
```

### Formatted output

[](#formatted-output)

To change the output format, use one of the `Output` implementations and pass a `Format` instance to the output's constructor. The formats available are:

- `DenseFormat($options)`: Best for network I/O, no unsignificant whitespace, default if nothing given and accessible via `Format::dense($options= ~Format::ESCAPE_SLASHES)`.
- `WrappedFormat($indent, $options)`: Wraps first-level arrays and all objects, uses whitespace after commas colons. An instance of this format using 4 spaces for indentation and per default leaving forward slashes unescaped is available via `Format::wrapped($indent= "    ", $options= ~Format::ESCAPE_SLASHES)`.

The available options that can be or'ed together are:

- `Format::ESCAPE_SLASHES`: Escape forward-slashes with "" - default behavior.
- `Format::ESCAPE_UNICODE`: Escape unicode with "\\uXXXX" - default behavior.
- `Format::ESCAPE_ENTITIES`: Escape XML entities `&`, `"`, ``. Per default, these are represented in their literal form.

```
use text\json\{FileOutput, Format};

$out= new FileOutput('glue.json', Format::wrapped());
$out->write([
  'name'    => 'example/package',
  'version' => '1.0.0',
  'require' => [
    'xp-forge/json'     => '^3.0',
    'xp-framework/core' => '^10.0'
  ]
]);
```

The above code will yield the following output:

```
{
    "name": "example/package",
    "version": "1.0.0'",
    "require": {
        "xp-forge/json": "^3.0",
        "xp-framework/core": "^10.0"
    }
}
```

Sequential processing
---------------------

[](#sequential-processing)

Processing elements sequentially can save you memory and give a better performance in certain situations.

### Reading

[](#reading)

You can use the `elements()` method to receive an iterator over a JSON array. Instead of loading the entire source into memory and then returning the parsed array, it will parse one array element at a time, yielding them while going.

```
use peer\http\HttpConnection;
use text\json\StreamInput;

$conn= new HttpConnection(...);
$in= new StreamInput($conn->get('/search?q=example&limit=1000')->in());
foreach ($in->elements() as $element) {
  // Process
}
```

If you get a huge object, you can also process it sequentially using the `pairs()` method. This will parse a single key/value pair at a time.

```
use peer\http\HttpConnection;
use text\json\StreamInput;

$conn= new HttpConnection(...);
$in= new StreamInput($conn->get('/resources/4711?expand=*')->in());
foreach ($in->pairs() as $key => $value) {
  // Process
}
```

To detect the type of the data on the stream (again, without reading it completely), you can use the `type()` method.

```
use peer\http\HttpConnection;
use text\json\StreamInput;

$conn= new HttpConnection(...);
$in= new StreamInput($conn->get($resource)->in());
$type= $in->type();
if ($type->isArray()) {
  // Handle arrays
} else if ($type->isObject()) {
  // Handle objects
} else {
  // Handle primitives
}
```

### Writing

[](#writing)

To write data sequentially, you can use the `begin()` method and the stream it returns. This makes sense when the source offers a way to read data sequentially, if you already have the entire data in memory, using `write()` has the same effect.

```
use text\json\{StreamOutput, Types};

$query= $conn->query('select * from person');

$stream= (new StreamOutput(...))->begin(Types::$ARRAY);
while ($record= $query->next()) {
  $stream->element($record);
}
$stream->close();
```

As the `Stream` class implements the Closeable interface, it can be used in the `with` statement:

```
use text\json\{StreamOutput, Types};

$query= $conn->query('select * from person');

with ((new StreamOutput(...))->begin(Types::$ARRAY), function($stream) use($query) {
  while ($record= $query->next()) {
    $stream->element($record);
  }
});
```

Further reading
---------------

[](#further-reading)

- [Performance figures](https://github.com/xp-forge/json/wiki/Performance-overview). TL;DR: While slower than the native functionality, the performance overhead is in low millisecond ranges. Using sequential processing we have an advantage both performance- and memory-wise.
- [Parsing JSON is a Minefield](http://seriot.ch/parsing_json.html). This library runs this test suite next to its own.

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance59

Moderate activity, may be stable

Popularity35

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity74

Established project with proven stability

 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

Every ~138 days

Recently: every ~257 days

Total

29

Last Release

277d ago

Major Versions

v1.0.1 → v2.0.02016-02-21

v2.3.1 → v3.0.02017-06-04

v3.1.2 → v4.0.02020-04-10

v4.1.0 → v5.0.02021-10-21

v5.1.0 → v6.0.02025-05-04

PHP version history (5 changes)v0.8.4PHP &gt;=5.4.0

v1.0.0PHP &gt;=5.5.0

v3.0.0PHP &gt;=5.6.0

v4.0.0PHP &gt;=7.0.0

v6.0.0PHP &gt;=7.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/07d18d882c8b4aaf3466432f64018214f2771eda333202175431ee7233795376?d=identicon)[thekid](/maintainers/thekid)

---

Top Contributors

[![thekid](https://avatars.githubusercontent.com/u/696742?v=4)](https://github.com/thekid "thekid (292 commits)")

---

Tags

jsonparsephp7php8streamxp-frameworkmodulexp

### Embed Badge

![Health badge](/badges/xp-forge-json/health.svg)

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

PHPackages © 2026

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