This commit is contained in:
nlohmann committed 2026-10-26 21:24:35 +00:00
1 parent 41c601a7d1
commit d2e264bd84
1400 files changed
+11859 -5440

No files matched your search

+22 -5
View File
@@ -13,6 +13,12 @@ to the current JSON value by executing all operations from the patch, yielding t
If the document is large and the original value is no longer needed,
[`patch_inplace`](../api/basic_json/patch_inplace.md) applies the same operations in place instead.
!!! note "Duplicate member names"
Duplicate member names inside an operation object are resolved by the parser before the patch is applied (the last
one is kept, see [`object_t`](../api/basic_json/object_t.md#behavior)), so
`#!json {"op": "add", "op": "remove", "path": "/a"}` is a `remove` operation.
??? example "Example: apply a JSON Patch"
The following code shows how a JSON patch is applied to a value.
@@ -22,7 +28,7 @@ to the current JSON value by executing all operations from the patch, yielding t
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using nlohmann::json;
using namespace nlohmann::literals;
int main()
@@ -49,7 +55,7 @@ to the current JSON value by executing all operations from the patch, yielding t
// output original and patched document
std::cout << std::setw(4) << doc << "\n\n"
<< std::setw(4) << patched_doc << std::endl;
<< std::setw(4) << patched_doc << '\n';
}
```
@@ -85,12 +91,23 @@ flowchart LR
!!! success "Invariant"
For two JSON values *source* and *target*, the following code yields always true:
For two JSON values *source* and *target*, the following code yields true:
```cpp
source.patch(diff(source, target)) == target;
```
The equality holds up to [`operator==`](../api/basic_json/operator_eq.md), with these exceptions:
- `NaN` and [discarded](../api/basic_json/is_discarded.md) values are not equal to themselves, so the invariant
cannot hold for them. `diff` emits a `replace` operation for such a value, and a `NaN` in a patch is serialized
as `#!json null`.
- Numbers that compare equal produce no operation even if their types differ: `diff(1, 1.0)`, `diff(1u, 1)`, and
`diff(0.0, -0.0)` return `#!json []`, so the patched value keeps the number type of *source*.
- A [binary value](binary_values.md) in a patch is serialized as an object
(`#!json {"bytes":[...],"subtype":null}`), so a patch that was dumped and parsed again no longer holds a binary
value.
??? example "Example: create a JSON Patch from the difference of two values"
The following code shows how a JSON patch is created as a diff for two JSON values.
@@ -100,7 +117,7 @@ flowchart LR
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using nlohmann::json;
using namespace nlohmann::literals;
int main()
@@ -131,7 +148,7 @@ flowchart LR
// output patch and roundtrip result
std::cout << std::setw(4) << patch << "\n\n"
<< std::setw(4) << patched_source << std::endl;
<< std::setw(4) << patched_source << '\n';
}
```