File: jsonpatch.md

package info (click to toggle)
jsoncons 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 17,584 kB
  • sloc: cpp: 136,382; sh: 33; makefile: 5
file content (88 lines) | stat: -rw-r--r-- 1,964 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
### jsonpatch extension

The jsonpatch extension implements the IETF standard [JavaScript Object Notation (JSON) Patch](https://tools.ietf.org/html/rfc6902)

<table border="0">
  <tr>
    <td><a href="apply_patch.md">apply_patch</a></td>
    <td>Apply JSON Patch operations to a JSON document.</td> 
  </tr>
  <tr>
    <td><a href="from_diff.md">from_diff</a></td>
    <td>Create a JSON patch from a diff of two JSON documents.</td> 
  </tr>
</table>

The JSON Patch IETF standard requires that the JSON Patch method is atomic, so that if any JSON Patch operation results in an error, the target document is unchanged.
The patch function implements this requirement by generating the inverse commands and building an undo stack, which is executed if any part of the patch fails.

### Examples

```cpp
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpatch/jsonpatch.hpp>

using jsoncons::json;
namespace jsonpatch = jsoncons::jsonpatch;

int main()
{
    // Apply a JSON Patch

    json doc = json::parse(R"(
        { "foo": "bar"}
    )");

    json doc2 = doc;

    json patch = json::parse(R"(
        [
            { "op": "add", "path": "/baz", "value": "qux" },
            { "op": "add", "path": "/foo", "value": [ "bar", "baz" ] }
        ]
    )");

    std::error_code ec;
    jsonpatch::apply_patch(doc, patch, ec);

    std::cout << "(1)\n" << pretty_print(doc) << '\n';

    // Create a JSON Patch from two JSON documents

    auto patch2 = jsonpatch::from_diff(doc2,doc);

    std::cout << "(2)\n" << pretty_print(patch2) << '\n';

    jsonpatch::apply_patch(doc2, patch2, ec);

    std::cout << "(3)\n" << pretty_print(doc2) << '\n';
}
```
Output:
```
(1)
{
    "baz": "qux",
    "foo": ["bar","baz"]
}
(2)
[
    {
        "op": "replace",
        "path": "/foo",
        "value": ["bar","baz"]
    },
    {
        "op": "add",
        "path": "/baz",
        "value": "qux"
    }
]
(3)
{
    "baz": "qux",
    "foo": ["bar","baz"]
}
```