vendredi 26 août 2022

Inserting more data into JSON file using nlohmann

I have a json file genrated in python from another system that needs to be read/updated in another MFC application. I can successfully read the existing data from the json file using nlohmann json add-in. For example, the file consists of two data fields with one field having any array of two subfields as below

{
  "city_data":[
     {
       "t":"m",
       "l":[12.0,10.3,0.0,1.0]
     },
     {
       "t":"l",
       "l":[10.1,20.37,0.0,1.0]
     },
     {
       "t":"l",
       "l":[47.82,4.63,0.0,1.0]
     },
     {
       "t":"m",
       "l":[67.66,43.33,0.0,1.0]
     }
  ],
  "map_data":"JZDKZTCaTyWQymUwmk8lkMplMJpPJZDKZTCaTyWQymUwmk/8/+n8AVAZ1WCxk8rYAAAAASUVORK5CYII="
}

I would like to add more entries into "city_data" field as {"t":"x","l":[0.0,0.0,0.0,0.0]} while the "map_data" stays the same. Then I can write the json object into a new file with updates.

To read the json file,

std::ifstream f(file);
json data = json::parse(f);

To retreive "city_data" and then its type and location

json& cityInfo = data["city_data"];
for (unsigned int i = 0; i < cityInfo.size(); i++)
        {
            json& cityType = cityInfo[i];
            json& cityLoc = cityType["l"];
            std::float_t x = cityLoc[0];
            std::float_t y = cityLoc[1];
            // ignoring the other two values for now
            std::string ctyTyp = cityType["t"];         
        }
f.close();

To retreive map data

ofstream outfile;
outfile.open(m_strFolderPath + m_strFileName + ".png", ofstream::binary);
std::string mapFrame = data["map_data"];
string temp = base64_decode(mapFrame );
outfile.write(temp.c_str(), temp.size());
outfile.close();

base64_decode is another function, not shown here as it is not relevant here.

Any suggestions on how to insert new city_data fields into the nlohmann JSON object?

Aucun commentaire:

Enregistrer un commentaire