Skip to content

Instantly share code, notes, and snippets.

@nariakiiwatani
Created August 23, 2019 06:24
Show Gist options
  • Save nariakiiwatani/3b6cb0057dff846ba040b7671a0a3fff to your computer and use it in GitHub Desktop.
Save nariakiiwatani/3b6cb0057dff846ba040b7671a0a3fff to your computer and use it in GitHub Desktop.
merge json obejcts using nlohmann::json
#pragma once
#include "json.hpp"
namespace json {
static nlohmann::json merge(nlohmann::json src, const nlohmann::json &append, bool overwrite_leaf, int depth=-1)
{
if(!src.is_object() || !append.is_object()) {
if(overwrite_leaf) {
return append;
}
else {
return src;
}
}
auto it = append.begin();
while(it != append.end()) {
auto found = src.find(it.key());
if(found != src.end()) {
if(depth != 0) {
found.value() = merge(found.value(), it.value(), overwrite_leaf, depth-1);
}
else if(overwrite_leaf) {
found.value() = it.value();
}
}
else {
src[it.key()] = it.value();
}
++it;
}
return src;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment