dopller
dopller

Reputation: 361

removing alphebatical reordering of key value pairs in nlohmann json

    nlohmann::json payload = {{"type", "market"},
            {"side", "buy"},
            {"product_id",market},
            {"funds", size}};
std::cout << payload.dump() << std::endl;
out : {"funds":"10","product_id":"BTC-USD","side":"buy","type":"market"} 

As you can see json is alphabetically reordered, which I dont want... How do I solve this ? thanks in advance!

Upvotes: 1

Views: 1184

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490178

You can use nlohmann::ordered_json instead of nlohmann::json to preserve the original insertion order:

    nlohmann::ordered_json payload = {{"type", "market"},
                {"side", "buy"},
                {"product_id","market"},
                {"funds", "size"}};
    std::cout << payload.dump() << std::endl;

Result:

{"type":"market","side":"buy","product_id":"market","funds":"size"}

I'd note, however, that in general, such mappings in json are inherently unordered, so if you really care about the order, this may not be the best choice for representing your data. You might be better off with (for example) an array of objects, each of which defines only a single mapping.

Upvotes: 3

Related Questions