0
    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!

dopller
  • 291
  • 3
  • 13

1 Answers1

1

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • thanks for replying... but I get this : error: ‘ordered_json’ in namespace ‘nlohmann’ does not name a type – dopller Jun 08 '22 at 02:08
  • I am using nlohmann json 3.10.5 version in cmake : ```include(FetchContent) FetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz) FetchContent_MakeAvailable(json)``` – dopller Jun 08 '22 at 02:11
  • @dopller: I only attempt to diagnose CMake problems when paid to do so, but the code above was tested with nlohmann json 3.10.5, just as you're using (on Ubuntu 20.04, using g++ 10.3, not that it's likely to matter). So it certainly *can* work when the software is all installed and working correctly. But achieving that with CMake can sometimes be more challenging than it should be. – Jerry Coffin Jun 08 '22 at 06:09