nlohmann库(C++)对json的读写增删改查
官网:Releases · nlohmann/json (github.com)
#include <iostream> #include "nlohmann/json.hpp" #include <fstream> using json = nlohmann::json; int main() { //写 json out = { {"pi",3.141}, {"happy",true}, {"name","Niels"}, {"nothing",nullptr}, {"list",{1,0,"2"}}, {"object0",{{"everything",42}}}, {"object1",{ {"currency","USD"}, {"value",42.99} }} }; std::ofstream o("0.json"); //o << std::setw(4) << out << std::endl; //格式化输出 o << out.dump(4) << std::endl; //格式化输出 //读 std::ifstream i("0.json"); json myJSON; i >> myJSON; std::cout << myJSON.dump(4) << std::endl; //查 std::cout << myJSON["list"] << std::endl; //查具体键的值 for (auto i = myJSON.begin(); i != myJSON.end(); i++) //查根目录的所有键。myJSON["object1"]查object1的所有键 { std::cout << "key:" << i.key() << std::endl; } //增 myJSON["pi2"] = 3.1415; myJSON["happy2"] = false; myJSON["list2"] = { "str",20 }; myJSON["object2"] = { {"currency","RMB"},{"value",233.1} }; std::cout << std::setw(4) << myJSON << std::endl; //改 myJSON["pi2"] = 5.15; myJSON["list"][1] = 5; //改数组的第2个元素 myJSON["object2"]["value"] = 230; //改object2的键value的值 std::cout << std::setw(4) << myJSON << std::endl; //删 myJSON.erase("pi2"); //删根目录的pi2键值对 myJSON["object2"].erase("value"); //删object2目录的value键值对 std::cout << myJSON.dump(4) << std::endl; }