This library implements RFC6902-compliant JSON patch tool.
- PHP 8.1.
- JSON extension (ext-json) - required by remorhaz/php-json-data to access JSON documents.
- 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
You can create accessible JSON document either from encoded JSON string or from decoded JSON data using corresponding node value factory:
use Remorhaz\JSON\Data\Value\EncodedJson;
use Remorhaz\JSON\Data\Value\DecodedJson;
// Creating document from JSON-encoded string:
$encodedValueFactory = EncodedJson\NodeValueFactory::create();
$encodedJson = '{"a":1}';
$document1 = $encodedValueFactory->createValue($encodedJson);
// Creating document from decoded JSON data:
$decodedValueFactory = DecodedJson\NodeValueFactory::create();
$decodedJson = (object) ['a' => 1];
$document2 = $decodedValueFactory->createValue($decodedJson);
You should use query factory to create query from JSON Patch document. Then you should use processor to apply that query:
<?php
use Remorhaz\JSON\Data\Value\EncodedJson;
use Remorhaz\JSON\Patch\Processor\Processor;
use Remorhaz\JSON\Patch\Query\QueryFactory;
$encodedValueFactory = EncodedJson\NodeValueFactory::create();
$queryFactory = QueryFactory::create();
$processor = Processor::create();
$patch = $encodedValueFactory->createValue('[{"op":"remove","path":"/0"}]');
$query = $queryFactory->createQuery($patch);
$document = $encodedValueFactory->createValue('[1,2]');
$result = $processor->apply($query, $document);
var_dump($result->encode()); // string: '[2]'
var_dump($result->decode()); // array: [2]
Note that result can be exported either to JSON-encoded string or to raw PHP value.
PHP JSON Patch is licensed under MIT license.