因为您没有指定语言标签,所以我继续并在c++中实现了它。
这是主程序:
int main()
{
auto jsonA = JSON::parse("{ \"a\":\"1\", \"b\":\"2\", \"c\":{\"a\":\"1\", \"b\":\"2\"} }");
auto jsonB = JSON::parse("{ \"b\":42, \"c\":{\"a\":\"1new\"}, \"q\":[3.14,null] }");
if (boost::apply_visitor(make_love(), jsonA, jsonB))
std::cout << "Merged: " << jsonA;
else
std::cerr << "Couldn't merge '" << jsonA << "' with '" << jsonB << "'\n";
}
输出:
Merged: {"a":"1","b":42,"c":{"a":"1new","b":"2"},"q":[3.14,null]}
当然,这只是引出了如何make_love
实现的问题:
struct make_love : boost::static_visitor<bool>
{
bool operator()(Object& a, Object const& b) const {
for(auto el: b.values)
recurse(a[el.first], el.second);
return true;
}
template<typename T, typename U> bool operator()(T& a, U const& b) const
{ return false; }
private:
void recurse(Value& a, Value const& b) const {
if (!boost::apply_visitor(*this, a, b))
a = b;
}
};
上下文中的完整代码(JSON.hpp/JSON.cpp):https ://github.com/sehe/spirit-v2-json/blob/q17711850/test.cpp