0

Using this line of code:

nlohmann::json msg_j = "{\"H\":\"1\",\"N\":3,\"D1\":3,\"D2\":150}"_json; 
std::string s = msg_j.dump();

I get as a result s:

{"D1":3,"D2":150,"H":"1","N":3}

Which is not in the desired order:

{"H":"1","N":3,"D1":3,"D2":150}

Please tell me how to get it, so I can finally solve my request for this post.

As JSON library for C++, I use nlohmann::json.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 3
    I don't think key/value pairs in JSON are supposed to be ordered. The receiving side should not care about the ordering. See https://stackoverflow.com/questions/16870416/does-the-sequence-of-the-values-matter-in-a-json-object. – user17732522 Apr 03 '23 at 18:50
  • Actually the order is important for me as this message has to be sent to a server via tcp/ip. –  Apr 03 '23 at 18:53
  • 2
    Are you sure the server cares about the order? – HolyBlackCat Apr 03 '23 at 18:55
  • 1
    See [`nlohmann::ordered_json`](https://json.nlohmann.me/api/ordered_json/). There is no corresponding user-defined literal type though, so you'll have to `parse` the string. – Miles Budnek Apr 03 '23 at 18:58
  • 2
    The server shouldn't care about the order either. `nlohmann::json` uses a `std::map` for its `ObjectType` by default. So the values will be ordered. – ChrisMM Apr 03 '23 at 18:59
  • A version of json for Arduino UNO is used on the server... What makes me angry that the same program written in python works fine, while this one in C++ fails :( –  Apr 03 '23 at 19:10
  • Nobody should care about the order of the values, as the JSON spec says: "*The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and **does not assign any significance to the ordering of name/value pairs**.*" – Remy Lebeau Apr 03 '23 at 19:17
  • You are all right. May I ask if you can help me convert the Python program into C++, perhaps by opening a new post ? I'm literally going crazy, I've been trying and trying for days, I don't know what to do anymore... –  Apr 03 '23 at 19:25
  • @giorgio Feel free to post specific questions about parts you're having trouble with. "Help me convert this python program to C++" would probably get closed as too broad. "I'm converting this python program to C++ and don't understand why this part doesn't work" is much more likely to get an answer. – Miles Budnek Apr 03 '23 at 19:39
  • Thanks for the tip Miles Budnek –  Apr 03 '23 at 20:01
  • @giorgio: Does this help. https://github.com/Loki-Astari/ThorsSerializer/blob/master/doc/example6.md – Martin York Apr 03 '23 at 21:56

0 Answers0