nlohmann库是C++解析json的库,库使用很简单。环境使用linux+kdevelop即可,程序中使用nlohmann仅需要将json.hpp添加到工程中即可。
介绍一下相关函数的使用。
json j_object = {{"one", 1}, {"two", 2}};
查找key:
可以用三种方式 find/at/下标
// call find1.find接口用的是迭代器,通过判断是否等于end()来判断键值是否存在
// print values
std::cout << std::boolalpha;
std::cout << "\"two\" was found: " << (it_two != j_object.end()) << '\n';
auto it_two = j_object.find("two");
2.使用at()接口会抛出异常,需要添加异常处理
try
{
// calling at() for a non-existing key
json j = {{"foo", "bar"}};
json k = j.at("non-existing");
}
catch (json::exception& e)
{
// output exception information
std::cout << "message: " << e.what() << '\n'
<< "exception id: " << e.id << std::endl;
}
打印结果
message: [json.exception.out_of_range.403] key 'non-existing' not found
exception id: 403
3.通过下标来访问
j_object["two"]=2
打印json对象内容:
j_object.dump(缩进量)
删除:
通过key删除
// call erase
auto count_one = j_object.erase("one");
通过索引删除
// create a JSON array
json j_array = {0, 1, 2, 3, 4, 5};
// call erase
j_array.erase(2);
// print values
std::cout << j_array << '\n';
结果
[1,2,8,16]
通过迭代器删除
j_array.erase(j_array.begin() + 2);