Search code examples
c++jsonjsoncpp

Generate a Json fil whith C++


I wrote a code in C++ to generate a .json file using the JsonCpp library. My issue is that I'm struggling to maintain the display order as it appears in the sequence of code within the file. Currently, the display order is alphabetical, which doesn't match the desired sequence. To resolve this and maintain the desired order, I'm wondering if there's a solution within the JsonCpp library or an alternative approach or library I should consider ?!

#include <iostream>
#include <fstream>
#include <jsoncpp/json/json.h>
#include <memory>

int main() {
    // Créer un objet Json::Value pour stocker les données
    Json::Value jsonData;

    // Enregistrement 1
    Json::Value enreg1;
    enreg1["CAT"] = "4";
    enreg1["Long"] = "19";
    enreg1["Day"] = "0";
    enreg1["Time"] = "13:15:37:86";
    enreg1["Fspec"] = "fa12gh";

    Json::Value Item1;
    Item1["AI"] = "1a";
    Item1["CC"] = "23";
    enreg1["Item1"] = Item1;

    // Ajouter Enreg_1 à l'objet JSON principal
    jsonData["Enreg_1"] = enreg1;

    // Ouvrir un fichier pour écrire le JSON
    std::ofstream file("do.json");

    if (file.is_open()) {
        // Utiliser un Writer de JsonCpp pour écrire l'objet JSON dans le fichier
        Json::StreamWriterBuilder builder;
        std::unique_ptr<Json::StreamWriter> jsonWriter(builder.newStreamWriter());

        // Écrire l'objet JSON dans le fichier
        jsonWriter->write(jsonData, &file);

        // Fermer le fichier
        file.close();
        std::cout << "Fichier JSON généré avec succès." << std::endl;
    } else {
        std::cerr << "Impossible d'ouvrir le fichier pour écrire." << std::endl;
        return 1;
    }

    return 0;
}

I expect this :

{
    "Enreg_1" : 
    {
        "CAT" : "4",
        "Long" : "19",
        "Day" : "0",
                "Time" : "13:15:37:86",
        "Fspec" : "fa12gh",
        "Item1" : 
        {
            "AI" : "1a",
            "CC" : "23"
        }
    }
}

But I have this instead (alphabetical order):

{
    "Enreg_1" : 
    {
        "CAT" : "4",
        "Day" : "0",
        "Fspec" : "fa12gh",
        "Item1" : 
        {
            "AI" : "1a",
            "CC" : "23"
        },
        "Long" : "19",
        "Time" : "13:15:37:86"
    }
}

Solution

  • As the commenters on your question have noted, JsonCPP uses an std::map to store its object members. If you switch to nlohmann::json you can override the backing store for objects to preserve insertion order.

    There is even a premade type for you to use:

    using ordered_json = nlohmann::ordered_json;