C++ 使用 nlohmann::json存儲json文件
- nlohmann::json 概述
- 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 響應和數據交換等。