@liveexample{The following code shows how a JSON patch is created as a diff for two JSON values.,diff}
26468 {
26469
26471
26472
26473 if (source == target)
26474 {
26475 return result;
26476 }
26477
26478 if (source.type() != target.type())
26479 {
26480
26481 result.push_back(
26482 {
26483 {"op", "replace"}, {"path", path}, {"value", target}
26484 });
26485 return result;
26486 }
26487
26488 switch (source.type())
26489 {
26491 {
26492
26493 std::size_t i = 0;
26494
26495 while (i < source.size() && i < target.size())
26496 {
26497
26498 auto temp_diff =
diff(source[i], target[i], path +
"/" + std::to_string(i));
26499 result.insert(result.end(), temp_diff.begin(), temp_diff.end());
26500 ++i;
26501 }
26502
26503
26504
26505
26507
26508 while (i < source.size())
26509 {
26510
26511
26512 result.insert(result.begin() + end_index,
object(
26513 {
26514 {"op", "remove"},
26515 {"path", path + "/" + std::to_string(i)}
26516 }));
26517 ++i;
26518 }
26519
26520
26521 while (i < target.size())
26522 {
26523 result.push_back(
26524 {
26525 {"op", "add"},
26526 {"path", path + "/-"},
26527 {"value", target[i]}
26528 });
26529 ++i;
26530 }
26531
26532 break;
26533 }
26534
26536 {
26537
26538 for (auto it = source.cbegin(); it != source.cend(); ++it)
26539 {
26540
26542
26543 if (target.find(it.key()) != target.end())
26544 {
26545
26546 auto temp_diff =
diff(it.value(), target[it.key()], path_key);
26547 result.insert(result.end(), temp_diff.begin(), temp_diff.end());
26548 }
26549
26550 else
26551 {
26552
26553 result.push_back(object(
26554 {
26555 {"op", "remove"}, {"path", path_key}
26556 }));
26557 }
26558 }
26559
26560
26561 for (auto it = target.cbegin(); it != target.cend(); ++it)
26562 {
26563 if (source.find(it.key()) == source.end())
26564 {
26565
26567 result.push_back(
26568 {
26569 {"op", "add"}, {"path", path_key},
26570 {"value", it.value()}
26571 });
26572 }
26573 }
26574
26575 break;
26576 }
26577
26586 default:
26587 {
26588
26589 result.push_back(
26590 {
26591 {"op", "replace"}, {"path", path}, {"value", target}
26592 });
26593 break;
26594 }
26595 }
26596
26597 return result;
26598 }
basic_json(const value_t v)
create an empty value with a given type
std::ptrdiff_t difference_type
a type to represent differences between iterators
static JSON_HEDLEY_WARN_UNUSED_RESULT basic_json object(initializer_list_t init={})
explicitly create an object from an initializer list
@ number_integer
number value (signed integer)
@ discarded
discarded by the parser callback function
@ binary
binary array (ordered collection of bytes)
@ object
object (unordered set of name/value pairs)
@ number_float
number value (floating-point)
@ number_unsigned
number value (unsigned integer)
@ array
array (ordered collection of values)
std::string escape(std::string s)
string escaping as described in RFC 6901 (Sect. 4)