Created
August 23, 2019 06:24
-
-
Save nariakiiwatani/3b6cb0057dff846ba040b7671a0a3fff to your computer and use it in GitHub Desktop.
merge json obejcts using nlohmann::json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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