废话不多说, 都是自己写的
hello_json.json
{
"listOfDict": [
{
"key1": "value1",
"key2": "value2"
},
{
"key1": "value1",
"key2": "value2"
}
]
}
main.cpp
//doc: https://github.com/nlohmann/json
# include <iostream>
# include"json.hpp" //download: https://github.com/nlohmann/json/releases/download/v3.9.1/json.hpp
# include <fstream>
using json = nlohmann::json;
int main(){
//how to create a empty json object
json j;
//read a json file and write it to json object
std::ifstream i("hello_json.json"); //# include <fstream>
i >> j;
//can we cout the json object?
std::cout << j << std::endl; //yes we can
//access the value of json object
std::cout << j["listOfDict"][0]["key1"] << std::endl;
//modify the value and check again
j["listOfDict"][0]["key1"] = "new_value1";
std::cout << j["listOfDict"][0]["key1"] << std::endl;
//save the json object as a new json file and check again
std::ofstream o("new_hello_json.json");
o << j << std::endl;
json new_j;
std::ifstream new_i("new_hello_json.json"); //# include <fstream>
new_i >> new_j;
std::cout << new_j << std::endl;
return 0;
}
最后获得的new_hello_json.json
{
"listOfDict": [
{
"key1": "new_value1",
"key2": "value2"
},
{
"key1": "value1",
"key2": "value2"
}
]
}