在 C++ 中解析 JSON 数据,你可以使用第三方库,例如 nlohmann/json
首先,确保你已经安装了 nlohmann/json 库。如果没有,请访问 https://github.com/nlohmann/json#integration 获取安装说明。
包含 json.hpp 头文件:
#include<iostream>#include <fstream>#include<string>#include "json.hpp"using json = nlohmann::json;using namespace std;从文件或字符串中读取 JSON 数据:// 从文件读取 JSON 数据ifstream ifs("example.json");json j = json::parse(ifs);// 从字符串读取 JSON 数据string json_str = R"({"name": "John", "age": 30, "city": "New York"})";json j = json::parse(json_str);访问 JSON 数据的值:// 获取 JSON 对象的键值对string name = j["name"];int age = j["age"];string city = j["city"];// 获取 JSON 数组的元素json arr = j["array"];for (const auto& elem : arr) { cout<< elem<< endl;}修改 JSON 数据的值:j["name"] = "Jane";j["age"] = 25;将 JSON 数据写入文件或字符串:// 将 JSON 数据写入文件ofstream ofs("output.json");ofs << j;// 将 JSON 数据转换为字符串string json_str = j.dump();这是一个完整的示例代码:
#include<iostream>#include <fstream>#include<string>#include "json.hpp"using json = nlohmann::json;using namespace std;int main() { // 从文件读取 JSON 数据 ifstream ifs("example.json"); json j = json::parse(ifs); // 访问 JSON 数据的值 string name = j["name"]; int age = j["age"]; string city = j["city"]; // 修改 JSON 数据的值 j["name"] = "Jane"; j["age"] = 25; // 将 JSON 数据写入文件 ofstream ofs("output.json"); ofs << j; return 0;}在这个示例中,我们从名为 example.json 的文件中读取 JSON 数据,访问其中的值,修改它们,然后将修改后的 JSON 数据写入名为 output.json 的文件。