jsoncpp insert object into document rather than append

1.2k views Asked by At

We are working with a partner that requires some fields to appear at the beginning of a JSON document. We build a document before knowing what this initial data will be and have been unable to find a way to insert it at the beginning. We have:

Json::Value json_message
json_message["singlestring"] = "blah blah blah"

then later a function gets this message

SomeFunction(Json::Value &json_message) {
   Json::Value sub_json;
   sub_json["one"] = "some sub 1";
   sub_json["two"] = "some sub 2";
   json_message["subobject"] = sub_json;
}

which results in

{
"singlestring":"blah blah blah",
"subobject":
{
"one":"some sub 1",
"two":"some sub 2",
}
}

but we need

{
"subobject":
{
"one":"some sub 1",
"two":"some sub 2",
},
"singlestring":"blah blah blah"
}

Is there a way to insert "subobject" to the beginning of the document, or to append the existing json_message to sub_json? Thank you

1

There are 1 answers

1
Sga On BEST ANSWER

That is not possible due to the internal representation of object members.

JsonCpp uses a std::map. When you serialize to string using FastWriter, if an object is found std::vector<JSONCPP_STRING> getMemberNames() is called, which puts in a vector the keys of the std::map.

To reach your goal you must modify getMemberNames(), assigning a "priority" to members of your liking (such as subobject).