This library implements RFC6902-compliant JSON patch tool.
- PHP 7.3+
- Internationalization functions (ext-intl) - required by
remorhaz/php-json-data
to compare Unicode strings.
You will need composer to perform install.
composer require remorhaz/php-json-patch
Patch tool utilizes JSON data accessor interfaces defined in package
remorhaz/php-json-data. Read more about them in package documentation.
There is a ready-to-work implementation in that package that works with native PHP structures (like the ones you get as
a result of json_decode
function). You can use Remorhaz\JSON\Data\Reference\Selector
class to bind to patch data and
Remorhaz\JSON\Data\Reference\Writer
class to bind to the document that is to be patched. You can also implement your own accessors
if you need to work with another sort of data (like unparsed JSON text, for example).
To apply JSON Patch to the JSON document you need just 4 simple steps:
- Create an instance of read-only accessor bound to your patch data.
- Create an instance of writabe accessor bound to your document.
- Create an object of
\Remorhaz\JSON\Patch\Patch
by calling it's constructor with a document accessor as an argument. - Call its
apply()
method with patch accessor as an argument.
<?php
use Remorhaz\JSON\Data\Reference\Selector;
use Remorhaz\JSON\Data\Reference\Writer;
use Remorhaz\JSON\Patch\Processor\Processor;
// Setting up document.
$data = (object) ['a' => (object) ['b' => 'c', 'd' => 'e']];
$dataWriter = new Writer($data);
// Setting up patch.
$patchData = [
(object) ['op' => 'add', 'path' => '/a/f', 'value' => 'g'],
];
$patchSelector = new Selector($patchData);
// Applying the patch.
(new Processor($dataWriter))->apply($patchSelector); // $data->a->f property is added and set to 'g'
PHP JSON Patch is licensed under MIT license.