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 89 90 91 92 93 94 95 96 97 98 99
|
### jsoncons::jsonpatch::apply_patch
```cpp
#include <jsoncons_ext/jsonpatch/jsonpatch.hpp>
template <typename Json>
void apply_patch(Json& target, const Json& patch); (1)
template <typename Json>
void apply_patch(Json& target, const Json& patch, std::error_code& ec); (2)
```
Applies a patch to a `json` document.
#### Return value
None
#### Exceptions
(1) Throws a [jsonpatch_error](jsonpatch_error.md) if `apply_patch` fails.
(2) Sets the out-parameter `ec` to the [jsonpatch_error_category](jsonpatch_errc.md) if `apply_patch` fails.
### Examples
#### Apply a JSON Patch with two add operations
```cpp
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpatch/jsonpatch.hpp>
using jsoncons::json;
namespace jsonpatch = jsoncons::jsonpatch;
int main()
{
json doc = json::parse(R"(
{ "foo": "bar"}
)");
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(target,patch,ec);
std::cout << pretty_print(target) << '\n';
}
```
Output:
```
{
"baz": "qux",
"foo": ["bar","baz"]
}
```
#### Apply a JSON Patch with three add operations, the last one fails
```cpp
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpatch/jsonpatch.hpp>
using jsoncons::json;
namespace jsonpatch = jsoncons::jsonpatch;
int main()
{
json target = json::parse(R"(
{ "foo": "bar"}
)");
json patch = json::parse(R"(
[
{ "op": "add", "path": "/baz", "value": "qux" },
{ "op": "add", "path": "/foo", "value": [ "bar", "baz" ] },
{ "op": "add", "path": "/baz/bat", "value": "qux" } // nonexistent target
]
)");
std::error_code ec;
jsonpatch::apply_patch(target, patch, ec);
std::cout << "(1) " << ec.message() << '\n';
std::cout << "(2) " << target << '\n';
}
```
Output:
```
(1) JSON Patch add operation failed
(2) {"foo":"bar"}
```
Note that all JSON Patch operations have been rolled back, and target is in its original state.
|