вывод в json nlohmann\json.hpp C++

как реализовать изменение данных в json файле с помщью nlohmann\json.hpp задача такова что надо создавать элементы и перезаписывать элементы с помошью библиотеки

// create an empty structure (null)
json j;

// add a number that is stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;

// add a Boolean that is stored as bool
j["happy"] = true;

// add a string that is stored as std::string
j["name"] = "Niels";

// add another null object by passing nullptr
j["nothing"] = nullptr;

// add an object inside the object
j["answer"]["everything"] = 42;

// add an array that is stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 };

// add another object (using an initializer list of pairs)
j["object"] = { {"currency", "USD"}, {"value", 42.99} };

// instead, you could also write (which looks very similar to the JSON above)
json j2 = {
  {"pi", 3.141},
  {"happy", true},
  {"name", "Niels"},
  {"nothing", nullptr},
  {"answer", {
    {"everything", 42}
  }},
  {"list", {1, 0, 2}},
  {"object", {
    {"currency", "USD"},
    {"value", 42.99}
  }}
};

и надо сделать примерно такое:

void function(string file,string obj,string text){
}

file - имя файла (data.json) obj - куда записываем(к примеру значение vasya к name то чтоб в .json было так)

{
    "something":"something Value",
    "something":"something Value",
    "name":"vasya",
    "something":"something Value",
}

или же если этого элемента нет то создать и присвоить значение. text - значение которое надо присвоить к obj.


Ответы (2 шт):

Автор решения: Strunder

Если кому то будет интересно то вот

**
void writeFileJson()
{
     //Root node  
    Json::Value root;
 
     //Root node attributes  
    root["name"] = Json::Value("shuiyixin");
    root["age"] = Json::Value(21);
    root["sex"] = Json::Value("man");
 
     //Child node  
    Json::Value friends;
 
     //Child node attributes  
    friends["friend_name"] = Json::Value("ZhaoWuxian");
    friends["friend_age"] = Json::Value(21);
    friends["friend_sex"] = Json::Value("man");
 
     //The child node hangs on the root node  
    root["friends"] = Json::Value(friends);
 
     //Array form  
    root["hobby"].append("sing");
    root["hobby"].append("run");
    root["hobby"].append("Tai Chi");
 
     //Direct output  
    //cout << "FastWriter:" << endl;
    //Json::FastWriter fw;
    //cout << fw.write(root) << endl << endl;
 
     //Indented output  
    cout << "StyledWriter:" << endl;
    Json::StyledWriter sw;
    cout << sw.write(root) << endl << endl;
 
     //Output to file  
    ofstream os;
    os.open("demo.json", std::ios::out | std::ios::app);
    if (!os.is_open())
        cout << "error:can not find or create the file which named \" demo.json\"." << endl;
    os << sw.write(root);
    os.close();
 }
**

Вот main

#include <string>  
#include <json.h>
#include <iostream>  
#include <fstream>  
using namespace std;
 
 void readStrJson(); //Read JSON from a string  
 void readStrProJson(); //Read JSON from a string (more complicated content)  
 void readFileJson(); //Read JSON from the file 
 void writeFileJson(); //Save the information as JSON format  
 
int main(int argc, char *argv[])
{
     writeFileJson(); //Write json
 
     readFileJson(); //Read JSON from the file 
 
    cout << "\n\n";
 
     readStrJson(); //Read json from the string
 
    cout << "\n\n";
 
     readStrProJson();//Read JSON from a string (the content is more complicated)  
    
    system("pause");
    return 0;
→ Ссылка
Автор решения: slavroman
os << sw.write(root);

вывод с отступами можно реализовать так:

os << std::setw(4) << root;

где 4 - количество пробелов для отступа.

→ Ссылка