Search code examples
c++nlohmann-json

i have a problem with putting information into a json type file


when i put

contact["name"] = name;
contact["lastname"] = lastname;
contact["address"] = address;
contact["email"] = email;
contact["number"] = number.

and i printed contact, its will always be in the order of address, email, lastname name and number

i try diffrent way like

std::string contactString = "{ \"name\": \"" + name + "\", \"lastname\": \"" + lastname + "\", \"address\": \"" + address + "\", \"email\": \"" + email + "\", \"number\": \"" + number + "\" }";

and make from string to json and save it but it will always be in ""adress, email,lastname,name and number order"" i was expecting to be in ""name,lastname,address,email,number order"" PLs try to best to help me out thank you!


Solution

  • When you set up your JSON object with keys like contact["name"] = name;, the order of the keys doesn't stay as you defined them.

    To fix this, you can use nlohmann::ordered_json instead of the regular nlohmann::json. This ensures that the keys are stored and printed in the order they were inserted.

    using ordered_json = nlohmann::ordered_json;
    
    int main() {
        std::string name = "John";
        std::string lastname = "Doe";
        std::string address = "1234 Elm Street";
        std::string email = "[email protected]";
        std::string number = "123-456-7890";
    
        // Create an ordered JSON object
        ordered_json contact;
        contact["name"] = name;
        contact["lastname"] = lastname;
        contact["address"] = address;
        contact["email"] = email;
        contact["number"] = number;
    
        // Print the ordered JSON object
        std::cout << contact.dump(4) << std::endl;
    
        return 0;
    }