Skip to content

How to merge (and not replace) different Json::Value objects in jsoncpp #2001

Description

@ashishsingh5

I have JSON config in Json::Value json_config of following format:

{
   "configuration":{
      "services":{
         "analytics":{
            "export-profile":[
               {
                  "name":"export_1000",
                  "transport":"grpc"
               }
            ],
            "sensor":[
               {
                  "name":"sensor_1000",
                  "export-name":"export_1000",
               }
            ]
         }
      }
   }
} 

How can I merge multiple similar above mentioned Json::Value such as below

{
   "configuration":{
      "services":{
         "analytics":{
            "export-profile":[
               {
                  "name":"export_1001",
                  "transport":"grpc"
               }
            ],
            "sensor":[
               {
                  "name":"sensor_1001",
                  "export-name":"export_1001",
               }
            ]
         }
      }
   }
} 

into one so that the final config looks something like below:

{
   "configuration":{
      "services":{
         "analytics":{
            "export-profile":[
               {
                  "name":"export_1000",
                  "transport":"grpc"
               },
               {
                  "name":"export_1001",
                  "transport":"grpc"
               },

               ...
            ],
            "sensor":[
               {
                  "name":"sensor_1000",
                  "export-name":"export_1000",
               },
               {
                  "name":"sensor_1001",
                  "export-name":"export_1001",
               },

               ...
            ]
         }
      }
   }
} 

I tried below, but it ends up replacing the previous config, and at the end only the last one remains.

void merge_json_objs (Json::Value& super, Json::Value& sub)
{
    // Merge all members of sub into super
    for (const auto& key : sub.getMemberNames()) {
        if (super[key].type() == Json::objectValue &&
            sub[key].type() == Json::objectValue) {
            merge_json_objects(super[key], sub[key]);
        } else {
            super[key] = sub[key];
        }
    }
}

OS: FreeBSD11,
compiler: gcc 4.2
JsonCpp version: 1.7.4

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions