How is the order of json fields produced by the C++ nlohmann json package determined

66 Views Asked by At

I have the following json file:

{
    "args":{"value":"192.168.30.4", "desc":"multi uhd device address args"},
    "file":{"value":"usrp_samples.dat", "desc":"output file"},
    "type":{"value":"short", "desc":"sample type: double, float or short"},
    "nsamps":{"value":"0", "desc":"total number of samples to recv"}
}

I am reading it with this C++ code:

#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
#include <string>

using json = nlohmann::json;

int main() {
    // Read from the JSON file using parse
    std::ifstream file("test3a.json");

    if (file.is_open()) {
        json json_data = json::parse(file);

        // Iterate over the keys of the JSON object
        for (auto it = json_data.begin(); it != json_data.end(); ++it) {
            // Accessing values from each key-value pair
            std::string key = it.key();
            json value = it.value();

            // Displaying the read data
            std::cout << "Input Var: " << key << std::endl;
            std::cout << "      Value: " << value["value"] << std::endl;
            std::cout << "      Desc : " << value["desc"] << std::endl;
           
            
        }
        std::cout << cmd_line << std::endl;
    } else {
        std::cerr << "Error opening file." << std::endl;
    }

However, the C++ output, reverses the order of the last two fields - i.e.:

Input Var: args
      Value: "192.168.30.4"
      Desc : "multi uhd device address args"
Input Var: file
      Value: "usrp_samples.dat"
      Desc : "output file"
Input Var: nsamps
      Value: "0"
      Desc : "total number of samples to recv"
Input Var: type
      Value: "short"
      Desc : "sample type: double, float or short"

Why is this? Is the ordering of these fields like a Python dict (i.e. no particular order is promised?)? Is there a way I can force the order of the C++ output to adhere to the same ordering as was in the source json file?

0

There are 0 best solutions below