0

I have an issue with JsonCpp library in C++ and sorting of keys after the json is produced. I found that JsonCpp is ignoring alphabetical order if there is Lowercase and Uppercase difference. It always favors Uppercase first and then alphabetical order.

Lets say we have this code to produce

Json::Value aJsonResult(Json::objectValue);

aJsonResult["ShuttersOpen"] = "test";
aJsonResult["ShutterType"] = "test";
aJsonResult["ShutterWidth"] = "test";

Json::StreamWriterBuilder aBuilder;
aBuilder["indentation"] = "";
return Json::writeString(aBuilder, aJsonResult).c_str();

But this produces output below, notice how ShuttersOpen key is last, even though its not correct.

{
    "ShutterType": "test",
    "ShutterWidth": "test",
    "ShuttersOpen": "test"
}

Any ideas how to fix this, I could not find any documentation on the official site

9
  • generally json is not ordered. Why is this an issue? Commented Aug 1, 2024 at 14:21
  • because of unit tests, I need to have it uniformed across the solution Commented Aug 1, 2024 at 14:22
  • 3
    but if it is not ordered, why you want to test that it is ordered? Commented Aug 1, 2024 at 14:24
  • 1
    Fix your tooling, you're depending on implementation details. One approach would be to use jq to pipe both expected and actual JSON through and then compare the result, so that you get similar formatting and ordering. Commented Aug 1, 2024 at 14:30
  • 1
    Just to confirm: JsonCpp has no way to impose order on map elements. nlohmann::json could be done that way, but I agree with others - unit tests should not add extra requirements to production code. If you have external JSON as expected value, parse it and compare parsed objects (ignoring order on map members). Commented Aug 1, 2024 at 14:35

1 Answer 1

2

In lexicographical order, capital letters precede lowercase letters. "Z" < "a".

Sign up to request clarification or add additional context in comments.

1 Comment

okay, got it, I was hoping there would something like in c# to make all keys lowercase and sort them when creating a json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.