权双
发布于 2026-06-04 / 21 阅读
0

nlohmann/json:像Python一样丝滑处理JSON

nlohmann/json是目前 C++ 中最流行的 JSON 库之一。它有header-only、零依赖等特性,接口设计的像在写原生Python一样好用。

1 环境配置

为了确保代码的跨平台兼容性与可移植性,本库采用 CMake 作为核心构建系统。以下是经过严格验证的演示环境配置。

📊 环境总览

🖥️ 平台🔧 硬件配置💿 操作系统⚙️ 编译器工具链
WindowsIntel Core i5‑13490FWindows 11 ProVisual Studio 2019 (MSVC v142)
LinuxRaspberry Pi 4BDebian GNU/Linux 13 (trixie)gcc/g++

📦 下载项目

项目地址:https://github.com/nlohmann/json
git拉取:

git clone https://github.com/nlohmann/json.git

⚙️ 文件目录结构

nlohmann/json支持header-only,无需编译,只需要include下的纯文本文件即可使用,目录结构如下:

└─include
    └─nlohmann
        │  adl_serializer.hpp
        │  byte_container_with_subtype.hpp
        │  json.hpp
        │  json_fwd.hpp
        │  ordered_map.hpp
        │
        ├─detail
        │  │  abi_macros.hpp
        │  │  exceptions.hpp
        │  │  ...(此处省略多个.hpp文件)
        │  │
        │  ├─conversions
        │  │      from_json.hpp
        │  │      to_chars.hpp
        │  │      to_json.hpp
        │  │
        │  ├─input
        │  │      binary_reader.hpp
        │  │      input_adapters.hpp
        │  │      ...(此处省略多个.hpp文件)
        │  │
        │  ├─iterators
        │  │      internal_iterator.hpp
        │  │      iteration_proxy.hpp
        │  │      ...(此处省略多个.hpp文件)
        │  │
        │  ├─meta
        │  │  │  cpp_future.hpp
        │  │  │  detected.hpp
        │  │  │  ...(此处省略多个.hpp文件)
        │  │  │
        │  │  └─call_std
        │  │          begin.hpp
        │  │          end.hpp
        │  │
        │  └─output
        │          binary_writer.hpp
        │          output_adapters.hpp
        │          serializer.hpp
        │
        └─thirdparty
            └─hedley
                    hedley.hpp
                    hedley_undef.hpp

✅看着目录结构比较复杂,但实际在使用时,仅需加载json.hpp这一个头文件即可。

如下所示

#include "json.hpp"

2 常用API

111

3 示例

✅ 一、核心判断函数(记住这 4 个)

判断函数
是否是对象 {}j.is_object()
是否是数组 []j.is_array()
是否是字符串j.is_string()
是否是数字j.is_number()
是否是布尔j.is_boolean()
是否是nullj.is_null()
是否存在某个 keyj.contains("key")

✅ 七、nlohmann/json 类型对照表

JSONC++ 类型
{}json::object_t
[]json::array_t
"abc"std::string
123int / double
true/falsebool
nullnullptr_t

你也可以这样判断:

if (j.type() == json::value_t::object) {}
if (j.type() == json::value_t::array) {}
{
  "website": {
    "url": "https://pgmpocket.com",
    "title": "pgmpocket",
    "description": "Focusing on program development, embedded, and artificial intelligence technology sharing.",
    "author": "quan shuang",
    "language": "zh",
    "keywords": ["embedded", "CUDA", "AI"],
    "date_published": "2026-06-04T08:30:00Z"
  }
}

2.1 读取

普通刚发:

#include <iostream>
#include <fstream>
#include <string>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // 打开 JSON 文件
    std::ifstream file("test.json");
    if (!file.is_open()) {
        std::cerr << "无法打开 website.json 文件" << std::endl;
        return 1;
    }

    try {
        // 解析 JSON
        json website;
        file >> website;

        // 访问 website 对象
        const auto& site = website["website"];

        std::cout << "URL: " << site["url"].get<std::string>() << std::endl;
        std::cout << "标题: " << site["title"].get<std::string>() << std::endl;
        std::cout << "描述: " << site["description"].get<std::string>() << std::endl;
        std::cout << "作者: " << site["author"].get<std::string>() << std::endl;
        std::cout << "语言: " << site["language"].get<std::string>() << std::endl;

        std::cout << "关键词: ";
        for (const auto& kw : site["keywords"]) {
            std::cout << kw.get<std::string>() << " ";
        }
        std::cout << std::endl;

        std::cout << "发布时间: " << site["date_published"].get<std::string>() << std::endl;
        std::cout << "Canonical URL: " << site["canonical_url"].get<std::string>() << std::endl;

    }
    catch (const json::exception& e) {
        std::cerr << "JSON 解析错误: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

from_json方法:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

// 网站信息结构体
struct Website {
    std::string url;
    std::string title;
    std::string description;
    std::string author;
    std::string language;
    std::vector<std::string> keywords;
    std::string date_published;
    std::string canonical_url;
};

// from_json 反序列化
void from_json(const json& j, Website& w) {
    j.at("url").get_to(w.url);
    j.at("title").get_to(w.title);
    j.at("description").get_to(w.description);
    j.at("author").get_to(w.author);
    j.at("language").get_to(w.language);
    j.at("keywords").get_to(w.keywords);
    j.at("date_published").get_to(w.date_published);
    j.at("canonical_url").get_to(w.canonical_url);
}

// 根对象
struct Root {
    Website website;
};

void from_json(const json& j, Root& r) {
    j.at("website").get_to(r.website);
}

int main() {
    std::ifstream file("test.json");
    if (!file) {
        std::cerr << "无法打开 test.json" << std::endl;
        return 1;
    }

    json j;
    file >> j;

    Root root = j.get<Root>();
    const auto& w = root.website;

    std::cout << "URL: " << w.url << std::endl;
    std::cout << "标题: " << w.title << std::endl;
    std::cout << "描述: " << w.description << std::endl;
    std::cout << "作者: " << w.author << std::endl;
    std::cout << "语言: " << w.language << std::endl;

    std::cout << "关键词: ";
    for (const auto& k : w.keywords) {
        std::cout << k << " ";
    }
    std::cout << std::endl;

    std::cout << "发布时间: " << w.date_published << std::endl;
    std::cout << "Canonical URL: " << w.canonical_url << std::endl;

    return 0;
}

2.2 写入

#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    json j;
    j["website"]["url"] = "https://example.com";
    j["website"]["title"] = "JSON";
    j["website"]["language"] = "zh";
    j["website"]["keywords"] = { "JSON", "SEO", "C++" };

    std::ofstream file("output.json");
    if (!file) {
        std::cerr << "无法写入文件" << std::endl;
        return 1;
    }

    file << j.dump(4); // 4 空格缩进
    return 0;
}
#include <string>
#include <vector>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

struct Website {
    std::string url;
    std::string title;
    std::string description;
    std::string author;
    std::string language;
    std::vector<std::string> keywords;
    std::string date_published;
    std::string canonical_url;
};

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(
    Website,
    url,
    title,
    description,
    author,
    language,
    keywords,
    date_published,
    canonical_url
)

int main() {
    Website w;
    w.url = "https://example.com/blog/json-metadata";
    w.title = "JSON";
    w.description = "JSON JSON JSON";
    w.author = "qs";
    w.language = "zh";
    w.keywords = { "JSON", "SEO", "config" };
    w.date_published = "2026-06-04T08:30:00Z";
    w.canonical_url = "https://example.com/blog/json-metadata";

    json j;
    j["website"] = w;

    std::ofstream file("website.json");
    file << j.dump(4);

    return 0;
}