Doubt how to take a JSON, turn it into an object

Asked

Viewed 332 times

0

I have a little doubt about a json module in c++, I wanted to know if there is any way to take a json that already exists and increment more fields using c++,

json data = json::parse(getData());
FILE * pFile;
pFile = fopen("data.json", "a");
fputs("", pFile);
fclose(pFile);

{
"0": {
"area": "SI",
"codigo_curso": "01",
"cpf": "000.000.000-00",
"data_nascimento": "00/00/0000",
"descricao": "Breve",
"endereco": "00000-000",
"nome": "Daniel Yohan"
}
}

wanted to add more of these here with changed values:

"0": {
"area": "SI",
"codigo_curso": "01",
"cpf": "000.000.000-00",
"data_nascimento": "00/00/0000",
"descricao": "Breve",
"endereco": "00000-000",
"nome": "Daniel Yohan"
}

I’m using the lib https://github.com/nlohmann/json

Would anyone know how to get me to upload my current json then add and save again? I’ll be grateful, this is for a college job. Thank you

  • And that lib is the one that is using of json?

  • like I said, I’m using the https://github.com/nlohmann/json library, there’s the json lib

  • Sorry when you said "I’m using json’s" I understood that it was a json file, now it’s clearer, see if the answer works please.

1 answer

1


I believe that as README is like this https://github.com/nlohmann/json#json-as-first-class-data-type, would look something like this:

json newitem = {
"area": "SI",
"codigo_curso": "02",
"cpf": "000.000.000-00",
"data_nascimento": "00/00/0000",
"descricao": "Breve",
"endereco": "00000-000",
"nome": "João"
};

json data = json::parse(getData());
data["1"] = newitem;

To record would change the a for w, or better exchange FILE for ofstream so you don’t have to keep making conversions and use dump() (or .dump(4) to put spacing) to convert to text:

string jsonstr = j.dump();

ofstream arq;
arq.open("data.json");
arq << jsonstr;
arq.close();

So it will update the current file

Browser other questions tagged

You are not signed in. Login or sign up in order to post.