JSON for Modern C++ 2.1.1
Loading...
Searching...
No Matches

◆ diff()

Creates a JSON Patch so that value source can be changed into the value target by calling patch function.

Invariant
For two JSON values source and target, the following code yields always true:
static basic_json array(std::initializer_list< basic_json > init=std::initializer_list< basic_json >())
explicitly create an array from an initializer list
Definition json.hpp:2165
static basic_json diff(const basic_json &source, const basic_json &target, const std::string &path="")
creates a diff as a JSON patch
Definition json.hpp:12222
basic_json patch(const basic_json &json_patch) const
applies a JSON patch
Definition json.hpp:11929
Note
Currently, only remove, add, and replace operations are generated.
Parameters
[in]sourceJSON value to compare from
[in]targetJSON value to compare against
[in]pathhelper value to create JSON pointers
Returns
a JSON patch to convert the source to target
Complexity\n Linear in the lengths of source and target.
Example\n The following code shows how a JSON patch is created as a
diff for two JSON values.
1#include <json.hpp>
2
3using json = nlohmann::json;
4
5int main()
6{
7 // the source document
8 json source = R"(
9 {
10 "baz": "qux",
11 "foo": "bar"
12 }
13 )"_json;
14
15 // the target document
16 json target = R"(
17 {
18 "baz": "boo",
19 "hello": [
20 "world"
21 ]
22 }
23 )"_json;
24
25 // create the patch
27
28 // roundtrip
30
31 // output patch and roundtrip result
32 std::cout << std::setw(4) << patch << "\n\n"
33 << std::setw(4) << patched_source << std::endl;
34}
a class to store JSON values
Definition json.hpp:1040
basic_json<> json
default JSON class
Definition json.hpp:12369

Output (play with this example online):
[
    {
        "op": "replace",
        "path": "/baz",
        "value": "boo"
    },
    {
        "op": "remove",
        "path": "/foo"
    },
    {
        "op": "add",
        "path": "/hello",
        "value": [
            "world"
        ]
    }
]

{
    "baz": "boo",
    "hello": [
        "world"
    ]
}

The example code above can be translated with
g++ -std=c++11 -Isrc doc/examples/diff.cpp -o diff 
See also
patch – apply a JSON patch
RFC 6902 (JSON Patch)
Since
version 2.0.0

Definition at line 12222 of file json.hpp.