json __0">nlohmann::json 核心函数和方法
1. 基础构造与初始化
函数/方法 描述 示例 json j;
创建一个空的 JSON 对象(默认是 object
类型) json j;
json ::object()
显式创建一个空的 JSON 对象 json j = json ::object();
json ::array()
显式创建一个空的 JSON 数组 json arr = json ::array();
json j = {...};
直接初始化 JSON 对象或数组 json j = {{"key", "value"}, {"arr", {1, 2}}};
json ::parse(json _str)
从字符串解析 JSON 数据 json j = json ::parse(R"({"name": "Alice"})");
json ::from_msgpack(data)
从 MessagePack 二进制数据解析 JSON json j = json ::from_msgpack(msgpack_data);
json ::from_bson(data)
从 BSON 二进制数据解析 JSON json j = json ::from_bson(bson_data);
2. 数据访问与修改
函数/方法 描述 示例 j[key]
访问或修改对象的键值(需确保键存在) j["age"] = 25;
j.at(key)
安全访问键值(若键不存在,抛出异常) std::string name = j.at("name");
j.value(key, default)
安全访问键值,若不存在返回默认值 int age = j.value("age", 0);
j.push_back(value)
向 JSON 数组末尾添加元素 j["hobbies"].push_back("coding");
j.emplace_back(args)
直接在数组末尾构造元素 j.emplace_back("new_item");
j.size()
返回对象或数组的元素数量 if (j.size() > 0) { ... }
j.empty()
检查 JSON 是否为空对象/数组 if (j.empty()) { ... }
j.contains(key)
检查对象是否包含指定键 if (j.contains("address")) { ... }
j.erase(key)
移除 JSON 对象的某个键 j.erase("age");
j.clear()
清空 JSON 对象或数组 j.clear();
3. 序列化与反序列化
函数/方法 描述 示例 j.dump(indent)
将 JSON 转为字符串(indent
控制缩进) std::string s = j.dump(4);
json ::parse(str)
从字符串解析 JSON json j = json ::parse(R"({"key": "value"})");
json ::to_msgpack(j)
将 JSON 转换为 MessagePack 格式 std::vector<uint8_t> msgpack = json ::to_msgpack(j);
json ::to_bson(j)
将 JSON 转换为 BSON 格式 std::vector<uint8_t> bson = json ::to_bson(j);
operator<< / operator>>
通过流读写 JSON 数据 std::ofstream("data.json ") << j; std::ifstream("data.json ") >> j;
4. 类型检查与转换
函数/方法 描述 示例 j.is_object()
/ j.is_array()
/ j.is_string()
检查 JSON 值的具体类型 if (j["age"].is_number()) { ... }
j.get<T>()
将 JSON 值转换为指定类型(需类型匹配) int age = j["age"].get<int>();
j.type_name()
获取 JSON 值的类型名称 std::string type = j.type_name();
5. 遍历与迭代
函数/方法 描述 示例 j.items()
返回对象的键值对迭代器(仅对对象有效) for (auto& [key, val] : j.items()) { ... }
j.begin() / j.end()
返回数组或对象的迭代器 for (auto it = j.begin(); it != j.end(); ++it) { ... }
j.keys()
获取对象的所有键 for (const auto& key : j.keys()) { ... }
6. 合并与修改
函数/方法 描述 示例 j.merge_patch(other)
合并两个 JSON 对象(覆盖重复键的值) j1.merge_patch(j2);
j.patch(json _patch)
应用 JSON Patch 修改操作 j = j.patch(patch);
j.flatten()
将嵌套 JSON 展开为扁平结构 json flat = j.flatten();
j.unflatten()
将扁平化 JSON 恢复为嵌套结构 json nested = flat.unflatten();
7. 示例代码
json j = { { "name" , "Alice" } , { "scores" , { 90 , 85 , 95 } } , { "metadata" , { { "version" , 1.0 } , { "active" , true } } }
} ;
std:: string json _str = j. dump ( 4 ) ;
json parsed = json :: parse ( json _str) ;
std:: string name = parsed. value ( "name" , "Unknown" ) ;
int score = parsed[ "scores" ] [ 0 ] . get < int > ( ) ;
json update = { { "metadata" , { { "version" , 2.0 } } } } ;
parsed. merge_patch ( update) ;