C++ 使用 nlohmann::json存储json文件
nlohmann::json 概述
nlohmann::json
是 C++ 中一个流行的 JSON 库,由 Niels Lohmann 开发。它提供了一个简单而强大的 API,用于解析、构建、操作和序列化 JSON 数据。
nlohmann::json
是一个模板类,可以用来表示 JSON 数据。它可以表示 JSON 对象、数组、数值、字符串、布尔值和空值等各种类型。nlohmann::json
支持方便的成员函数和操作符重载,使得对 JSON 数据的访问和修改非常直观和简便。
JSON 存储的示例
#include <iostream>
#include <fstream>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
int main() {
// 创建一个复杂的嵌套 JSON 对象
json data = {
{
"name", "John"},
{
"age", 30},
{
"is_student", false},
{
"grades", {
85, 92, 78, 90}},
{
"address", {
{
"street", "123 Main St"},
{
"city", "New York"},
{
"country", "USA"}
}},
{
"friends", {
{
{
"name", "Alice"}, {
"age", 28}},
{
{
"name", "Bob"}, {
"age", 32}},
{
{
"name", "Claire"}, {
"age", 27}}
}}
};
// 将 JSON 对象写入文件
std::ofstream file("data.json");
if (file.is_open()) {
file << std::setw(4) << data << std::endl;
file.close();
std::cout << "JSON data has been written to file." << std::endl;
} else {
std::cerr << "Failed to open file for writing." << std::endl;
}
return 0;
}
以追加的方式存储json文件
在打开文件时使用 std::ofstream 的 std::ios_base::app 模式来追加写入数据。
std::ofstream json_out_file_("data.json", std::ios_base::app);
以下是 nlohmann::json
常见的用法和功能:
-
解析和构建 JSON 数据:
nlohmann::json json_data = nlohmann::json::parse(json_string); // 解析 JSON 字符串为 JSON 对象 nlohmann::json json_data = { { "key", "value" }, { "array", { 1, 2, 3} }}; // 构建 JSON 对象 // 在 JSON 对象中添加新的字段或修改现有字段 json_data["new_key"] = "new_value"; json_data["existing_key"] = 123; // 创建 JSON 数组 nlohmann::json json_array = { 1, 2, 3, 4, 5};
-
访问和操作 JSON 数据:
std::string value = json_data["key"]; // 获取 JSON 对象中指定字段的值 int size = json_array.size(); // 获取 JSON 数组的长度 bool is_object = json_data.is_object(); // 检查 JSON 数据是否为对象 // 遍历 JSON 对象或数组的元素 for (const auto& element : json_data) { std::string key = element.first; nlohmann::json value = element.second; // 处理元素 } // 修改 JSON 数组的元素 json_array[2] = 10;
-
序列化和反序列化 JSON 数据:
std::string serialized_json = json_data.dump(); // 将 JSON 对象序列化为字符串 // 从文件中读取 JSON 数据并解析 std::ifstream input_file("data.json"); nlohmann::json json_data; input_file >> json_data;
nlohmann::json
提供了一种便捷和高效的方式来处理 JSON 数据,使得在 C++ 程序中解析、生成和操作 JSON 变得更加简单。它非常适合于处理各种 JSON 数据,包括配置文件、API 响应和数据交换等。