• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Object Order
2
3The [JSON standard](https://tools.ietf.org/html/rfc8259.html) defines objects as "an unordered collection of zero or more name/value pairs". As such, an implementation does not need to preserve any specific order of object keys.
4
5The default type `nlohmann::json` uses a `std::map` to store JSON objects, and thus stores object keys **sorted alphabetically**.
6
7??? example
8
9    ```cpp
10    #include <iostream>
11    #include "json.hpp"
12
13    using json = nlohmann::json;
14
15    int main()
16    {
17        json j;
18        j["one"] = 1;
19        j["two"] = 2;
20        j["three"] = 3;
21
22        std::cout << j.dump(2) << '\n';
23    }
24    ```
25
26    Output:
27
28    ```json
29    {
30      "one": 1,
31      "three": 3,
32      "two": 2
33    }
34    ```
35
36If you do want to preserve the **insertion order**, you can try the type [`nlohmann::ordered_json`](https://github.com/nlohmann/json/issues/2179).
37
38??? example
39
40    ```cpp
41    #include <iostream>
42    #include <nlohmann/json.hpp>
43
44    using ordered_json = nlohmann::ordered_json;
45
46    int main()
47    {
48        ordered_json j;
49        j["one"] = 1;
50        j["two"] = 2;
51        j["three"] = 3;
52
53        std::cout << j.dump(2) << '\n';
54    }
55    ```
56
57    Output:
58
59    ```json
60    {
61      "one": 1,
62      "two": 2,
63      "three": 3
64    }
65    ```
66
67Alternatively, you can use a more sophisticated ordered map like [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) ([integration](https://github.com/nlohmann/json/issues/546#issuecomment-304447518)) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map) ([integration](https://github.com/nlohmann/json/issues/485#issuecomment-333652309)).
68