PHPackages                             funkyoz/json-stream - 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. funkyoz/json-stream

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

funkyoz/json-stream
===================

High-performance PHP library for streaming JSON parsing with constant memory usage.

1.2.0(2mo ago)10160↓50%MITPHPPHP ^8.1CI passing

Since Dec 11Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/FunkyOz/json-stream)[ Packagist](https://packagist.org/packages/funkyoz/json-stream)[ Fund](https://www.buymeacoffee.com/funkyoz)[ GitHub Sponsors](https://github.com/FunkyOz)[ RSS](/packages/funkyoz-json-stream/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (12)Versions (12)Used By (0)

JsonStream PHP
==============

[](#jsonstream-php)

A high-performance PHP library for streaming JSON parsing, designed to handle arbitrarily large JSON files with constant memory usage.

[![PHP Version](https://camo.githubusercontent.com/1a5e13126d38c1d05f712dae30e7f60ae0444a9c882e9e526349ccba27facb8d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e312d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE.md)[![Tests](https://camo.githubusercontent.com/d940ad7f0752e2cbe0d63c50dcebf329078807390051c41fe63258f1b5c4e182/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d70617373696e672d627269676874677265656e)](tests/)[![Coverage](https://camo.githubusercontent.com/32855e94577df9d0a30995653b17d33a5fbfdf644518f96ea0374313397d19b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e)](tests/)

Why JsonStream?
---------------

[](#why-jsonstream)

Traditional JSON parsing with `json_decode()` loads the entire file into memory, which fails on large files. JsonStream uses a streaming approach that processes JSON incrementally, maintaining **constant memory usage** regardless of file size.

### Key Benefits

[](#key-benefits)

- **Memory Efficient**: Process multi-GB JSON files with ~100KB memory usage
- **Fast**: Iterator-based API for immediate data access without upfront parsing
- **JSONPath Support**: Filter and extract specific data without loading everything
- **Type Safe**: Full PHP 8.1+ type declarations with 100% type coverage
- **Zero Dependencies**: Pure PHP implementation, no extensions required

Performance Comparison
----------------------

[](#performance-comparison)

OperationJsonStreamjson\_decode()1MB file~100KB RAM~3MB RAM100MB file~100KB RAM**FAILS** (out of memory)1GB file~100KB RAM**FAILS** (out of memory)Speed~1.5-2x slowerBaseline**When to use JsonStream:**

- Files larger than available memory
- Processing large arrays/objects incrementally
- Streaming data from APIs or network
- Need to start processing before full download

**When to use json\_decode():**

- Small files (&lt; 10MB) that fit in memory
- Need random access to data structure
- Maximum speed is critical

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

[](#requirements)

- PHP 8.1 or higher
- No external dependencies or extensions

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

[](#installation)

Install via Composer:

```
composer require funkyoz/json-stream
```

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

[](#quick-start)

### Reading Large Arrays

[](#reading-large-arrays)

Process large JSON arrays without loading everything into memory:

```
use JsonStream\JsonStream;

// Read a large array incrementally
$reader = JsonStream::read('large-data.json');

foreach ($reader->readArray() as $item) {
    // Process each item immediately
    echo "ID: {$item['id']}, Name: {$item['name']}\n";

    // Memory usage stays constant!
}

$reader->close();
```

Usage Examples
--------------

[](#usage-examples)

### 1. JSONPath Filtering

[](#1-jsonpath-filtering)

Extract specific data using JSONPath expressions:

```
use JsonStream\JsonStream;

// Only read items matching the JSONPath expression
$reader = JsonStream::read('data.json', [
    'jsonPath' => '$.users[*]'  // Only extract users array items
]);

foreach ($reader->readArray() as $user) {
    echo "User: {$user['name']}\n";
}

$reader->close();
```

**Supported JSONPath expressions:**

- Simple paths: `$.users[*]`, `$.data.items[*]`
- Array indices: `$.users[0]`, `$.users[5]`
- Array slices: `$.users[0:10]`, `$.users[10:]`
- Wildcards: `$.users[*].name`
- Nested wildcards: `$.users[*].posts[*]`, `$.matrix[*][*]`

### 2. Pagination with Skip/Limit

[](#2-pagination-with-skiplimit)

Process specific ranges of data efficiently:

```
use JsonStream\JsonStream;

$reader = JsonStream::read('data.json');

// Skip first 100 items, read next 50
foreach ($reader->readArray()->skip(100)->limit(50) as $item) {
    echo "Item: {$item['id']}\n";
}

$reader->close();
```

### 3. Nested Object Iteration

[](#3-nested-object-iteration)

Read nested JSON objects:

```
use JsonStream\JsonStream;

$reader = JsonStream::read('config.json');

// Iterate over object key-value pairs
foreach ($reader->readObject() as $key => $value) {
    echo "Config '$key': $value\n";
}

$reader->close();
```

### 4. Reading from String

[](#4-reading-from-string)

Parse JSON from a string:

```
use JsonStream\JsonStream;

$json = '{"users": [{"id": 1}, {"id": 2}]}';
$reader = JsonStream::read($json);

foreach ($reader->readArray('$.users[*]') as $user) {
    echo "User ID: {$user['id']}\n";
}

$reader->close();
```

### 5. Error Handling

[](#5-error-handling)

Handle parsing errors gracefully:

```
use JsonStream\JsonStream;
use JsonStream\Exception\ParseException;
use JsonStream\Exception\IOException;

try {
    $reader = JsonStream::read('data.json');

    foreach ($reader->readArray() as $item) {
        // Process item
    }

    $reader->close();

} catch (IOException $e) {
    // File not found or not readable
    echo "IO Error: {$e->getMessage()}\n";

} catch (ParseException $e) {
    // Invalid JSON syntax
    echo "Parse Error: {$e->getMessage()}\n";
    echo "At position: {$e->getPosition()}\n";
}
```

Configuration Options
---------------------

[](#configuration-options)

### Reader Options

[](#reader-options)

```
$reader = JsonStream::read('data.json', [
    'bufferSize' => 32768,        // Buffer size in bytes (default: 8192)
    'maxDepth' => 512,            // Maximum nesting depth (default: 512)
    'jsonPath' => '$.data[*]'     // JSONPath filter (default: null)
]);
```

### Buffer Size Recommendations

[](#buffer-size-recommendations)

- Small files (&lt; 1MB): 8KB (default)
- Medium files (1-100MB): 16-32KB
- Large files (&gt; 100MB): 32-64KB
- Very large files (&gt; 1GB): 64KB-1MB

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

[](#api-reference)

### JsonStream

[](#jsonstream)

**Main Method:**

- `JsonStream::read(resource|string $input, array $options = []): StreamReader`
    - Accepts file path, JSON string, or stream resource
    - Automatically detects input type and creates appropriate reader

**Reading Methods (via returned StreamReader):**

- `readArray(): ArrayIterator` - Iterate over array items
- `readObject(): ObjectIterator` - Iterate over object properties
- `readItems(): ItemIterator` - Iterate over items (array or object)
- `readAll(): mixed` - Read entire structure into memory (use with caution)
- `readAllMatches(): array` - Read all items matching JSONPath filter

**Iterator Methods:**

- `skip(int $count): self` - Skip N items
- `limit(int $count): self` - Limit to N items
- `count(): int` - Count total items

**Utility Methods:**

- `close(): void` - Close the reader and free resources

Testing
-------

[](#testing)

Run the complete test suite:

```
composer tests
```

This runs:

- Code style checks (Laravel Pint)
- Type coverage checks (100% required)
- Static analysis (PHPStan)
- Unit tests (Pest)
- Integration tests

### Individual Test Commands

[](#individual-test-commands)

```
composer tests:unit           # Unit tests only
composer tests:integration    # Integration tests only
composer tests:coverage       # Coverage report (100% required)
composer tests:types          # Static analysis
composer tests:benchmark      # Performance benchmarks
```

Performance Benchmarks
----------------------

[](#performance-benchmarks)

Run performance benchmarks:

```
composer tests:benchmark
```

This tests:

- Memory usage vs file size
- Speed comparison with native JSON functions
- Buffer size impact
- JSONPath filtering performance

Project Quality
---------------

[](#project-quality)

This project maintains strict quality standards:

- **100% Type Coverage**: All code has complete type declarations
- **100% Code Coverage**: All code is covered by tests
- **Zero Style Violations**: Code passes Laravel Pint formatting
- **Zero Static Analysis Errors**: Code passes PHPStan checks at max level

Known Limitations
-----------------

[](#known-limitations)

- JSONPath support is limited to common patterns (see JSONPath Filtering section)
- Complex filter expressions `$[?(@.price < 10)]` are not yet supported
- Streaming is ~1.5-2x slower than native `json_decode()` for small files

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

[](#contributing)

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Write tests for new features
4. Ensure all quality checks pass: `composer tests`
5. Submit a pull request

Bug Reports
-----------

[](#bug-reports)

Found a bug? Please [open an issue](https://github.com/funkyoz/json-stream/issues) with:

- PHP version
- Code example reproducing the issue
- Expected vs actual behavior
- Sample JSON data if applicable

License
-------

[](#license)

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

Author
------

[](#author)

Lorenzo Dessimoni ()

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for version history and release notes.

Further Reading
---------------

[](#further-reading)

- [Development Guide](DEVELOPMENT.md) - For contributors
- [Examples](examples/) - More usage examples

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance86

Actively maintained with recent releases

Popularity21

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity50

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

Every ~29 days

Total

4

Last Release

70d ago

PHP version history (2 changes)1.0.0PHP &gt;=8.1 &lt;8.5

1.1.1PHP ^8.1

### Community

Maintainers

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

---

Top Contributors

[![FunkyOz](https://avatars.githubusercontent.com/u/26649880?v=4)](https://github.com/FunkyOz "FunkyOz (36 commits)")

---

Tags

streamphpjsonjson-stream

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/funkyoz-json-stream/health.svg)

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

###  Alternatives

[adhocore/json-fixer

Fix/repair truncated JSON data

51543.2k2](/packages/adhocore-json-fixer)[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)[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)
