Is there an elegant way to cascade merge two JSON trees using jsoncpp?

I am using jsoncpp to read settings from a JSON file.

I would like to have two cascading settings files, for example MasterSettings.json and MasterSettings.json , where LocalSettings is a subset of MasterSettings. I would like to download MasterSettings first and then LocalSettings. If LocalSettings has a value other than MasterSettings, this value will overwrite one of the MasterSettings. Very similar to cascading in CSS.

Is there an elegant way to do this using jsoncpp?

+6
source share
1 answer

I am going to assume that your settings files are JSON objects.

As you can see here , when JSONCpp parses the file, it clears the contents of the root node. This means that trying to parse a new file over the old one will not save the old data. However, if you parse both files in separate Json :: Value nodes, directly redraw them yourself, iterating over the keys in the second object using getMemberNames .

 // Recursively copy the values of b into a. Both a and b must be objects. void update(Json::Value& a, Json::Value& b) { if (!a.isObject() || !b.isObject()) return; for (const auto& key : b.getMemberNames()) { if (a[key].isObject()) { update(a[key], b[key]); } else { a[key] = b[key]; } } } 
+6
source

All Articles