nlohmann/json 是主流 c++ json 解析库,头文件即用、支持 c++11+,可从文件或字符串解析 json,支持键值/数组/嵌套访问、类型安全获取、异常处理及美化序列化输出。

用 C++ 解析 JSON 文件,nlohmann/json 是目前最主流、最易上手的第三方库。它头文件即用、无需编译,支持现代 C++(C++11 起),语法简洁直观,像写 Python 一样操作 JSON。
一、快速安装与配置
该库是纯头文件库,无需编译安装:
- 从 GitHub 下载单个头文件 json.hpp(推荐方式):
→ 访问 https://www.php.cn/link/b82e68e6366d4177332acdf3fa4d1e3a → 找到single_include/nlohmann/json.hpp→ 直接下载保存到项目 include 目录 - 或用包管理器(如 vcpkg):
vcpkg install nlohmann-json,然后在 CMake 中 link - 在源文件中包含:
#include "nlohmann/json.hpp"
(若用 vcpkg,通常为#include <nlohmann></nlohmann>)
二、基础解析:读取 JSON 文件内容
使用 nlohmann::json 类型自动解析字符串或文件流:
- 从文件读取并解析(推荐用
std::ifstream):
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
std::ifstream file("config.json");
if (!file.is_open()) {
throw std::runtime_error("无法打开 config.json");
}
json j;
file >> j; // 自动解析,支持 UTF-8(含 BOM)
- 也可从字符串解析:
json j = json::parse(R"({"name":"Alice","age":30})"); - 解析失败会抛出
nlohmann::json::parse_error异常,建议加 try-catch
三、访问 JSON 数据:键值、数组、嵌套结构
支持类似 Python 的点号/方括号语法,类型安全且带运行时检查:
立即学习“C++免费学习笔记(深入)”;
- 访问对象字段(string/int/bool 等):
std::string name = j["name"]; // 自动类型转换
int age = j["age"].get<int>(); // 显式获取(更安全)</int> - 检查字段是否存在:
if (j.contains("email")) { ... }或if (!j["email"].is_null()) { ... } - 访问数组元素:
double first_score = j["scores"][0];
for (auto& item : j["items"]) { ... } // 范围 for 遍历 - 处理嵌套对象:
std::string city = j["address"]["city"];<br> std::vector<std::string> tags = j["metadata"]["tags"].get<std::vector<std::string>>();
四、序列化输出:生成 JSON 字符串或写入文件
反向操作同样简单,支持美化格式和紧凑格式:
- 转为字符串:
std::string s = j.dump(); // 紧凑格式
std::string pretty = j.dump(2); // 缩进 2 空格 - 写入文件:
std::ofstream out("output.json");<br> out << j.dump(2) << std::endl; - 构造新 JSON 对象(动态构建):
json user;<br> user["id"] = 1001;<br> user["tags"] = {"cpp", "json"};<br> user["active"] = true;
不复杂但容易忽略:确保编译器启用 C++11 或更高标准(如 -std=c++11),并在读写文件时注意路径和编码(Windows 下建议用 UTF-8 无 BOM 或显式指定 locale)。











