400 8949 560

NEWS/新闻

分享你我感悟

您当前位置> 主页 > 新闻 > 技术开发

如何用c++解析JSON文件 nlohmann/json库的使用教程【第三方库】

发表时间:2026-01-06 00:00:00

文章作者:裘德小鎮的故事

浏览次数:

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

用 C++ 解析 JSON 文件,nlohmann/json 是目前最主流、最易上手的第三方库。它头文件即用、无需编译,支持现代 C++(C++11 起),语法简洁直观,像写 Python 一样操作 JSON。

一、快速安装与配置

该库是纯头文件库,无需编译安装:

  • 从 GitHub 下载单个头文件 json.hpp(推荐方式):
      → 访问 https://www./link/b82e68e6366d4177332acdf3fa4d1e3a → 找到 single_include/nlohmann/json.hpp → 直接下载保存到项目 include 目录
  • 或用包管理器(如 vcpkg):
      vcpkg install nlohmann-json,然后在 CMake 中 link
  • 在源文件中包含:
      #include "nlohmann/json.hpp"
      (若用 vcpkg,通常为 #include

二、基础解析:读取 JSON 文件内容

使用 nlohmann::json 类型自动解析字符串或文件流:

  • 从文件读取并解析(推荐用 std::ifstream):
#include 
#include 

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 的点号/方括号语法,类型安全且带运行时检查:

  • 访问对象字段(string/int/bool 等):
      std::string name = j["name"]; // 自动类型转换
      int age = j["age"].get(); // 显式获取(更安全)
  • 检查字段是否存在:
      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"];
    std::vector tags = j["metadata"]["tags"].get>();

四、序列化输出:生成 JSON 字符串或写入文件

反向操作同样简单,支持美化格式和紧凑格式:

  • 转为字符串:
      std::string s = j.dump(); // 紧凑格式
      std::string pretty = j.dump(2); // 缩进 2 空格
  • 写入文件:
      
    std::ofstream out("output.json");
    out << j.dump(2) << std::endl;
  • 构造新 JSON 对象(动态构建):
      
    json user;
    user["id"] = 1001;
    user["tags"] = {"cpp", "json"};
    user["active"] = true;

不复杂但容易忽略:确保编译器启用 C++11 或更高标准(如 -std=c++11),并在读写文件时注意路径和编码(Windows 下建议用 UTF-8 无 BOM 或显式指定 locale)。

相关案例查看更多