Creating an alphabetically sorted nlohmann::json subobject inside a nlohmann::ordered_json

78 Views Asked by At

Background Info

The nlohmann JSON library offers two object orders:

  1. nlohmann::json, which is alphabetically sorted
  2. nlohmann::ordered_json, which keeps the order of insertion

So if we do this:

    nlohmann::ordered_json outer;
    outer["b"] = "b";
    outer["a"] = "a";

a dump would look like this (Order of insertion):

{
 "b": "b",
 "a": "a"
}

But with a nlohmann::json it becomes (Alphabetical Order of the Keys):

{
 "a": "a",
 "b": "b"
}

What I want

I would like to mix the two orders. There should be an outer ordered_json which contains an inner json. A first naive try:

    nlohmann::ordered_json outer;
    outer["inner"] = nlohmann::json::object();
    outer["inner"]["b"] = "b";
    outer["inner"]["a"] = "a";

did not lead to the expected Result. Actual result:

{
 "inner": {
  "b": "b",
  "a": "a"
 }
}

What I have hoped for:

{
 "inner": {
  "a": "a",
  "b": "b"
 }
}

Is it possible to mix these two behaviors?

Why I want it

I am aware that the JSON Standard states that a JSON Object is an unordered collection of key/value pairs. However, I am currently in a "but the customer wants it" scenario. I am also aware that I could add the inner values in an alphabetical order myself in the above toy example. However, knowing the exact keys isn't a luxury I have in the real project. Finding out which keys will be added at runtime and then sorting them myself before adding them to the JSON isn't possible either, as it would require massive refactoring of the project itself.

What I found out so far

The operator[] seems to not care about the object that is about to be assigned while creating the subobject. When operator= is then called, it basically only moves existing Data in. So the following actually does lead to the expected result:

    nlohmann::ordered_json outer;
    nlohmann::json inner;
    inner["b"] = "b";
    inner["a"] = "a";
    outer["inner"] = inner;

However, this would again lead to a lot of refactoring. I would like the types to somehow "remember" their order.

0

There are 0 best solutions below