nlohmann/json是目前 C++ 生态中最流行的 JSON 库之一。header-only(单头文件)、零依赖、接口像写原生 JS/Python 一样自然,支持 C++11+。
1 环境配置
1️⃣ 下载项目
项目地址:
👉 GitHub - nlohmann/json: JSON for Modern C++ · GitHub
git拉取:
git clone https://github.com/nlohmann/json.git
2️⃣ 文件需求说明
无需编译,只需要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
│ │ hash.hpp
│ │ json_custom_base_class.hpp
│ │ json_pointer.hpp
│ │ json_ref.hpp
│ │ macro_scope.hpp
│ │ macro_unscope.hpp
│ │ string_concat.hpp
│ │ string_escape.hpp
│ │ string_utils.hpp
│ │ value_t.hpp
│ │
│ ├─conversions
│ │ from_json.hpp
│ │ to_chars.hpp
│ │ to_json.hpp
│ │
│ ├─input
│ │ binary_reader.hpp
│ │ input_adapters.hpp
│ │ json_sax.hpp
│ │ lexer.hpp
│ │ parser.hpp
│ │ position_t.hpp
│ │
│ ├─iterators
│ │ internal_iterator.hpp
│ │ iteration_proxy.hpp
│ │ iterator_traits.hpp
│ │ iter_impl.hpp
│ │ json_reverse_iterator.hpp
│ │ primitive_iterator.hpp
│ │
│ ├─meta
│ │ │ cpp_future.hpp
│ │ │ detected.hpp
│ │ │ identity_tag.hpp
│ │ │ is_sax.hpp
│ │ │ logic.hpp
│ │ │ std_fs.hpp
│ │ │ type_traits.hpp
│ │ │ void_t.hpp
│ │ │
│ │ └─call_std
│ │ begin.hpp
│ │ end.hpp
│ │
│ └─output
│ binary_writer.hpp
│ output_adapters.hpp
│ serializer.hpp
│
└─thirdparty
└─hedley
hedley.hpp
hedley_undef.hpp
✅ 无需 .lib,无需编译
仅仅看着目录结构复杂,实际在使用时,仅需加载json.hpp这一个头文件即可。
#include "json.hpp"
using json = nlohmann::json;
2 示例
✅ 一、核心判断函数(记住这 4 个)
| 判断 | 函数 |
|---|---|
是否是对象 {} | j.is_object() |
是否是数组 [] | j.is_array() |
| 是否是字符串 | j.is_string() |
| 是否是数字 | j.is_number() |
| 是否是布尔 | j.is_boolean() |
| 是否是null | j.is_null() |
| 是否存在某个 key | j.contains("key") |
✅ 七、nlohmann/json 类型对照表
| JSON | C++ 类型 |
|---|---|
{} | json::object_t |
[] | json::array_t |
"abc" | std::string |
123 | int / double |
true/false | bool |
null | nullptr_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;
}