PHPackages                             blancks/fast-jsonpatch-php - 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. blancks/fast-jsonpatch-php

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

blancks/fast-jsonpatch-php
==========================

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

v2.1.0(1y ago)396.4k↓20.1%1[1 PRs](https://github.com/blancks/fast-jsonpatch-php/pulls)MITPHPPHP &gt;=8.1

Since Aug 22Pushed 5mo ago3 watchersCompare

[ Source](https://github.com/blancks/fast-jsonpatch-php)[ Packagist](https://packagist.org/packages/blancks/fast-jsonpatch-php)[ Docs](https://github.com/blancks/fast-jsonpatch-php)[ RSS](/packages/blancks-fast-jsonpatch-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (3)Versions (10)Used By (0)

PHP Fast JSON Patch
===================

[](#php-fast-json-patch)

[![Test](https://github.com/blancks/fast-jsonpatch-php/workflows/Test/badge.svg)](https://github.com/blancks/fast-jsonpatch-php/blob/main/.github/workflows/test.yml)[![phpstan](https://github.com/blancks/fast-jsonpatch-php/workflows/phpstan/badge.svg)](https://github.com/blancks/fast-jsonpatch-php/blob/main/phpstan.neon.dist)[![codecov](https://camo.githubusercontent.com/de77b91b7e4740b082d126465eb45ece36c4bc210bd3121485fda2263263774e/68747470733a2f2f636f6465636f762e696f2f6769746875622f626c616e636b732f666173742d6a736f6e70617463682d7068702f67726170682f62616467652e7376673f746f6b656e3d33505543355241505051)](https://codecov.io/github/blancks/fast-jsonpatch-php)[![Maintainability](https://camo.githubusercontent.com/ab333efd574ad454d6640c222de4cab53a9c6e4c64b3e533a587aadfe5aefdd8/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f39323736356233343130653230646339613433312f6d61696e7461696e6162696c697479)](https://codeclimate.com/github/blancks/fast-jsonpatch-php/maintainability)[![PHP Version Require](https://camo.githubusercontent.com/c6ef76ae5f08c7ed87f7e6e70b3eee57e9035e6c0a3598cb6d7807200e9820d8/68747470733a2f2f706f7365722e707567782e6f72672f626c616e636b732f666173742d6a736f6e70617463682d7068702f726571756972652f706870)](https://packagist.org/packages/blancks/fast-jsonpatch-php)[![Latest Stable Version](https://camo.githubusercontent.com/86940a27822b029df13d361b61b5b1197fbc6c505e68f5477925bb5ecbcdf26f/68747470733a2f2f706f7365722e707567782e6f72672f626c616e636b732f666173742d6a736f6e70617463682d7068702f76)](https://packagist.org/packages/blancks/fast-jsonpatch-php)

This documentation covers the `FastJsonPatch` PHP class, designed to apply a series of JSON Patch operations as specified in [RFC 6902](https://datatracker.ietf.org/doc/html/rfc6902).

Fast JSON Patch is the fastest fully RFC compliant package available in PHP, you can find compliance test and benchmark results [here](https://github.com/blancks/php-jsonpatch-benchmarks).

Installation via Composer
-------------------------

[](#installation-via-composer)

```
composer require blancks/fast-jsonpatch-php
```

Class Overview
--------------

[](#class-overview)

The `FastJsonPatch` class provides a way to modify JSON documents using a structured patch object.
The patch object contains an array of operations (`add`, `remove`, `replace`, `move`, `copy`, and `test`) that describe the changes to be made to the target JSON document.

### Usage Example

[](#usage-example)

Below is an example of how to use the `FastJsonPatch` class to apply a patch to a JSON document:

```
use blancks\JsonPatch\FastJsonPatch;
use blancks\JsonPatch\exceptions\FastJsonPatchException;

$document = '{
    "contacts":[
        {"name":"John","number":"-"},
        {"name":"Dave","number":"+1 222 333 4444"}
    ]
}';

$patch = '[
    {"op":"add","path":"/contacts/-","value":{"name":"Jane", "number":"+1 353 644 2121"}},
    {"op":"replace","path":"/contacts/0/number","value":"+1 212 555 1212"},
    {"op":"remove","path":"/contacts/1"}
]';

$FastJsonPatch = FastJsonPatch::fromJson($document);

try {

    $FastJsonPatch->apply($patch);

} catch (FastJsonPatchException $e) {

    // here if patch cannot be applied for some reason
    echo $e->getMessage(), "\n";

}

var_dump($FastJsonPatch->getDocument());
```

**Expected Output:**

```
object(stdClass) (1) {
  ["contacts"]=>
  array(2) {
    [0]=>
    object(stdClass) (2) {
      ["name"]=>
      string(4) "John"
      ["number"]=>
      string(15) "+1 212 555 1212"
    }
    [1]=>
    object(stdClass) (2) {
      ["name"]=>
      string(4) "Jane"
      ["number"]=>
      string(15) "+1 353 644 2121"
    }
  }
}
```

The expected workflow is that once you got a `FastJsonPatch` instance you can call the `apply` method each time a new patch is received and this is particularly handy in long-running context like a websocket client/server.

Patch application is designed to be atomic. If any operation of a given patch fails the original document is restored, ensuring a consistent state of the document.

Constructor
-----------

[](#constructor)

#### `__construct(mixed &$document, ?JsonHandlerInterface $JsonHandler = null, ?JsonPointerHandlerInterface $JsonPointerHandler = null)`

[](#__constructmixed-document-jsonhandlerinterface-jsonhandler--null-jsonpointerhandlerinterface-jsonpointerhandler--null)

- **Description**: Initializes a new instance of the `FastJsonPatch` class.
- **Parameters**:
    - `mixed &$document`: The decoded JSON document.
    - `?JsonHandlerInterface $JsonHandler`: An instance of the JSON handler which will be responsible for encoding/decoding and CRUD operations.
        The default handler is `blancks\JsonPatch\json\handlers\BasicJsonHandler` and decodes json objects as php \\stdClass instances. This is the recommended way.
        If you application requires working with associative arrays only, you can pass a `blancks\JsonPatch\json\handlers\ArrayJsonHandler` instance instead.
    - `?JsonPointerHandlerInterface $JsonPointerHandler`: Instance of the object responsible to validate and parse JSON Pointers.
        The default handler is `blancks\JsonPatch\json\pointer\JsonPointer6901`
- **Returns**: Instance of the `FastJsonPatch` class.
- **Example**: ```
    $document = ['one', 'two', 'three'];
    $FastJsonPatch = new FastJsonPatch($document);
    ```

Public Methods
--------------

[](#public-methods)

#### `static function fromJson(string $patch, ?JsonHandlerInterface $JsonHandler = null, ?JsonPointerHandlerInterface $JsonPointerHandler = null) : void`

[](#static-function-fromjsonstring-patch-jsonhandlerinterface-jsonhandler--null-jsonpointerhandlerinterface-jsonpointerhandler--null--void)

- **Description**: Returns a new instance of the `FastJsonPatch` class.
- **Parameters**:
    - `string $document`: A json encoded document to which the patches will be applied
    - `?JsonHandlerInterface $JsonHandler`: An instance of the JSON handler which will be responsible for encoding/decoding and CRUD operations.
        The default handler is `blancks\JsonPatch\json\handlers\BasicJsonHandler` and decodes json objects as php \\stdClass instances. This is the recommended way.
        If you application requires working with associative arrays only, you can pass a `blancks\JsonPatch\json\handlers\ArrayJsonHandler` instance instead.
    - `?JsonPointerHandlerInterface $JsonPointerHandler`: Instance of the object responsible to validate and parse JSON Pointers.
        The default handler is `blancks\JsonPatch\json\pointer\JsonPointer6901`
- **Example**: ```
    $FastJsonPatch = FastJsonPatch::fromJson('{"foo":"bar","baz":["qux","quux"]}');
    ```

#### `function apply(string $patch) : void`

[](#function-applystring-patch--void)

- **Description**: Applies a series of patch operations to the specified JSON document. Ensures atomicity by applying all operations successfully or restoring the original document if any operation fails.
- **Parameters**:
    - `string $patch`: A json-encoded array of patch operations.
- **Exceptions**:
    - Throws `FastJsonPatchValidationException` if a patch operation is invalid or improperly formatted.
    - Throws `FastJsonPatchException` if any other error occurs while applying the patch
- **Example**: ```
    $patch = '[{"op":"test", "path":"/foo", "value":"bar"}]';
    $FastJsonPatch->apply($patch);
    ```

#### `function isValidPatch(string $patch): bool`

[](#function-isvalidpatchstring-patch-bool)

- **Description**: Tells if the $patch is syntactically valid
- **Parameters**:
    - `string $patch`: A json-encoded array of patch operations.
- **Returns**: True is the patch is valid, false otherwise
- **Example**: ```
    $patch = '[{"op":"add","path":"/foo"}]'; // invalid because there's no "value" key

    if ($FastJsonPatch->isValidPatch($patch)) {
        $FastJsonPatch->apply($patch);
    } else {
        echo "Invalid patch!";
    }
    ```

#### `function read(string $path): mixed`

[](#function-readstring-path-mixed)

- **Description**: Uses a JSON Pointer (RFC-6901) to fetch data from the referenced document
- **Parameters**:
    - `string $patch`: A json pointer
- **Returns**: The value located by the provided pointer
- **Example**: ```
    $FastJsonPatch = FastJsonPatch::fromJson('{"foo":"bar","baz":["qux","quux"]}');
    echo $FastJsonPatch->read('/baz/1'); // "quux"
    ```

#### `function &getDocument(): mixed`

[](#function-getdocument-mixed)

- **Description**: Returns the document reference that the instance is holding
- **Returns**: The referenced document
- **Example**: ```
    $FastJsonPatch = FastJsonPatch::fromJson('["qux","quux"]');
    var_dump($FastJsonPatch->getDocument()); // array(2) {[0]=> string(3) "qux" [1]=> string(4) "quux"}
    ```

#### `function registerOperation(PatchOperationInterface $PatchOperation): void`

[](#function-registeroperationpatchoperationinterface-patchoperation-void)

- **Description**: Allows to register new patch operation handlers or to override existing ones.
- **Parameters**:
    - `PatchOperationInterface $PatchOperation`: The handler class for handling the operation.
- **Example**: ```
    $FastJsonPatch->registerOperation(new Add);
    ```

Supported Operations
--------------------

[](#supported-operations)

#### `add`

[](#add)

- **Description**: Adds a value to the specified path in the document.
- **Parameters**:
    - `path`: JSON Pointer to the location where the value should be added.
    - `value`: The value to add.
- **Example**: ```
    {"op":"add","path":"/new/key","value":"example"}
    ```

#### `remove`

[](#remove)

- **Description**: Removes the value at the specified path.
- **Parameters**:
    - `path`: JSON Pointer to the location of the value to remove.
- **Example**: ```
    {"op":"remove","path":"/old/key"}
    ```

#### `replace`

[](#replace)

- **Description**: Replaces the value at the specified path with a new value.
- **Parameters**:
    - `path`: JSON Pointer to the location of the value to replace.
    - `value`: The new value.
- **Example**: ```
    {"op":"replace","path":"/replace/key","value":"newValue"}
    ```

#### `move`

[](#move)

- **Description**: Moves the value from one path to another.
- **Parameters**:
    - `from`: JSON Pointer to the source location of the value to move.
    - `path`: JSON Pointer to the destination location.
- **Example**: ```
    {"op":"move","from":"/old/key","path":"/new/key"}
    ```

#### `copy`

[](#copy)

- **Description**: Copies the value from one path to another.
- **Parameters**:
    - `from`: JSON Pointer to the source location of the value to copy.
    - `path`: JSON Pointer to the destination location.
- **Example**: ```
    {"op":"copy","from":"/source/key","path":"/target/key"}
    ```

#### `test`

[](#test)

- **Description**: Tests that the specified value matches the value at the path.
- **Parameters**:
    - `path`: JSON Pointer to the location of the value to test.
    - `value`: The value to compare.
- **Example**: ```
    {"op":"test","path":"/test/key","value":"expectedValue"}
    ```

Running tests
-------------

[](#running-tests)

```
composer test
```

Test cases comes from [json-patch/json-patch-tests](https://github.com/json-patch/json-patch-tests) and extended furthermore to ensure a strict compliance with RFC-6902.

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

[](#contributing)

Contributions are welcome! 🎉
Feel free to fork the repository if you'd like to contribute to this project!

Please ensure your contributions align with the project's goals and code style:

- Use `composer run static-analyse` for static analysis
- Use `composer run pretty-php` to reformat your code before commit
- Provide unit tests for the code you wrote, this project targets 100% coverage
- It is ok to write alternative handlers to address slower operations, such as working with huge json files
- Any changes that hurts the package performance in its default configuration must be motivated with a good reason

If you have any questions, need guidance, reporting a bug or suggesting an improvement feel free to open an issue. Every bit helps!

Thank you for helping to improve this project!

License
-------

[](#license)

This software is licensed under the [MIT License](LICENSE.md).

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance58

Moderate activity, may be stable

Popularity35

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity54

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 ~17 days

Recently: every ~28 days

Total

8

Last Release

516d ago

Major Versions

v1.2.3 → v2.0.02024-11-06

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1021441?v=4)[Salvatore](/maintainers/blancks)[@blancks](https://github.com/blancks)

---

Top Contributors

[![blancks](https://avatars.githubusercontent.com/u/1021441?v=4)](https://github.com/blancks "blancks (107 commits)")

---

Tags

phpjsonjson patch

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/blancks-fast-jsonpatch-php/health.svg)

```
[![Health](https://phpackages.com/badges/blancks-fast-jsonpatch-php/health.svg)](https://phpackages.com/packages/blancks-fast-jsonpatch-php)
```

###  Alternatives

[php-jsonpatch/php-jsonpatch

Implementation of JSON Patch (http://tools.ietf.org/html/rfc6902)

981.2M6](/packages/php-jsonpatch-php-jsonpatch)[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)[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)
