Home > Blockchain >  removing alphebatical reordering of key value pairs in nlohmann json
removing alphebatical reordering of key value pairs in nlohmann json

Time:06-09

    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!

CodePudding user response:

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.

  • Related