JSON for Modern C++  3.0.0

◆ diff()

template<template< typename, typename, typename... > class ObjectType = std::map, template< typename, typename... > class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template< typename > class AllocatorType = std::allocator, template< typename, typename=void > class JSONSerializer = adl_serializer>
static basic_json nlohmann::basic_json::diff ( const basic_json source,
const basic_json target,
const std::string &  path = "" 
)
inlinestatic

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:
source.patch(diff(source, target)) == target;
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
Linear in the lengths of source and target.
Example
The following code shows how a JSON patch is created as a diff for two JSON values.
1 #include <iostream>
2 #include "json.hpp"
3 
4 using json = nlohmann::json;
5 
6 int main()
7 {
8  // the source document
9  json source = R"(
10  {
11  "baz": "qux",
12  "foo": "bar"
13  }
14  )"_json;
15 
16  // the target document
17  json target = R"(
18  {
19  "baz": "boo",
20  "hello": [
21  "world"
22  ]
23  }
24  )"_json;
25 
26  // create the patch
27  json patch = json::diff(source, target);
28 
29  // roundtrip
30  json patched_source = source.patch(patch);
31 
32  // output patch and roundtrip result
33  std::cout << std::setw(4) << patch << "\n\n"
34  << std::setw(4) << patched_source << std::endl;
35 }
basic_json<> json
default JSON class
Definition: json.hpp:14353
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:14213
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 14213 of file json.hpp.