答案是使用nlohmann/json库解析JSON。1. 引入json.hpp头文件;2. 用std::ifstream读取文件;3. 通过nlohmann::json::parse解析内容,捕获异常处理错误。

在C++中解析和生成JSON数据,由于标准库不直接支持JSON操作,通常需要借助第三方库来完成。目前最常用且易于使用的库是 nlohmann/json(也叫 JSON for Modern C++)。它使用简单、头文件-only,无需编译,非常适合中小型项目。
1. 引入 nlohmann JSON 库
这个库是 header-only 的,意味着你只需要下载一个头文件并包含即可使用。
步骤:2. 解析 JSON 文件
以下是一个读取本地 JSON 文件并解析内容的示例:
#include <iostream>
#include <fstream>
#include <string>
#include "json.hpp"
// 使用命名空间简化代码
using json = nlohmann::json;
int main() {
// 打开 JSON 文件
std::ifstream file("data.json");
if (!file.is_open()) {
std::cerr << "无法打开文件!" << std::endl;
return -1;
}
// 解析 JSON 数据
json j;
try {
file >> j;
} catch (const std::exception& e) {
std::cerr << "JSON 解析失败:" << e.what() << std::endl;
return -1;
}
// 访问数据(假设 JSON 是对象)
std::string name = j["name"];
int age = j["age"];
std::vector<std::string> hobbies = j["hobbies"];
std::cout << "姓名: " << name << "\n";
std::cout << "年龄: " << age << "\n";
std::cout << "爱好: ";
for (const auto& h : hobbies) {
std::cout << h << " ";
}
std::cout << "\n";
return 0;
}
说明:
-
file >> j自动将文件内容解析为 JSON 对象 - 支持自动类型转换,如字符串、整数、数组等
- 使用 try-catch 捕获格式错误或缺失字段异常
3. 构建和序列化 JSON 数据
你也可以用代码构造 JSON 对象,并写入文件:
立即学习“C++免费学习笔记(深入)”;
json j;
j["name"] = "张三";
j["age"] = 25;
j["is_student"] = false;
j["hobbies"] = {"读书", "游泳", "编程"};
// 输出为字符串(带缩进)
std::string output = j.dump(4); // 参数 4 表示缩进空格数
std::cout << output << std::endl;
// 写入文件
std::ofstream out("output.json");
out << j.dump(2);
out.close();
4. 处理复杂结构(嵌套对象/数组)
JSON 经常包含嵌套结构,nlohmann/json 支持链式访问:
json config;
std::ifstream cfg_file("config.json") >> config;
// 假设 JSON 中有:{"server": {"host": "127.0.0.1", "port": 8080}}
std::string host = config["server"]["host"];
int port = config["server"]["port"];
// 遍历数组对象
for (auto& user : config["users"]) {
std::cout << "用户: " << user["name"] << ", ID: " << user["id"] << "\n";
}
该库还支持 STL 风格的迭代、自定义类型序列化等高级功能。
基本上就这些。只要引入 nlohmann/json,C++ 处理 JSON 就变得非常直观和安全。推荐用于大多数现代 C++ 项目(需支持 C++11 及以上)。











