示例代码:
nlohmann::json json = nlohmann::json::parse("{\"name\":\"zhangsan\",\"age\":43,\"subjects\":[\"chinese\",\"english\"]}");//解析json数据
if (json.find("age") != json.end())//查找属性
json["age"] = 56;//修改属性值
if (json.find("name") != json.end())
json["name"] = "lisi";
json["country"] = "USA";//添加新的字符串属性
nlohmann::json fam = nlohmann::json::parse("[\"father\", \"mother\"]");//临时待加入的json数组
json["family"] = fam;//添加新的数组属性
std::string resule = json.dump();//json变为字符串
if (json["country"].is_array() == false)//判断是否是数组
json.erase("country");//删除属性
if (json["family"].is_array() == true)
int humans = json["family"].size();//获取数组元素个数
resule = json.dump();
void testJson()
nlohmann::json json = nlohmann::json::parse("{\"data\":{\"d1\":\"d1_value\",\"d2\":2},\"name\":\"zhangsan\",\"age\":43,\"subjects\":[\"chinese\",\"english\"]}");//解析json数据
if (json.find("age") != json.end())//查找属性
json["age"] = 56;//修改属性值
std::string agetemp = json["age"].dump();
agetemp = json["subjects"].dump();
agetemp = "";
if (json.find("name") != json.end())
json["name"] = "lisi";
json["country"] = "USA";//添加新的属性
nlohmann::json fam = nlohmann::json::parse("[\"father\", \"mother\"]");
json["family"] = fam;//添加新的数组属性
std::string resule = json.dump();//json变为字符串
if (json["country"].is_array() == false)//判断是否是数组
json.erase("country");//删除属性
if (json["family"].is_array() == true)
int humans = json["family"].size();//获取数组元素个数
//两种获取字符串值的方式
if (json["family"].is_string())
std::string str = json["family"].get<std::string>();
std::string str = json["family"].get<std::string>();
int ageis = json["age"];
nlohmann::json testjson = nlohmann::json::parse("{\"test\":\"test_value\"}");
for (nlohmann::json::iterator it = json["data"].begin(); it != json["data"].end(); ++it) {
std::cout << it.key() << " : " << it.value() << "\n";
testjson[it.key()] = it.value();
std::string teststr = testjson.dump();
resule = json.dump();