开源库nlohmann json使用备忘

nlohmann/json是一个用于解析JSON的开源C++库,口碑一流,无需额外安装其他第三方库,还支持单个头文件模式,使用起来非常方便直观。

1. 编译

从官网https://github.com/nlohmann/json的Release页面下载单个json.hpp即可直接使用,无需单独编译。

2. 使用示例

下面以示例的方式罗列nlohmann/json库的基本使用方法。

2.1 生成JSON

方式1

cpp 复制代码
int main()
{
    using json = nlohmann::json;

    json j;
    j["pi"] = 3.141;
    j["happy"] = true;
    j["name"] = "Niels";
    j["nothing"] = nullptr;
    j["answer"]["everything"] = 42;
    j["list"] = { 1, 0, 2 };
    j["object"] = { {"currency", "USD"}, {"value", 42.99} };

    // 转成字符串
    std::string strJSON = j.dump(2); // 2个空格的缩进

    std::cout << strJSON;
    return 0;
}

输出如下:

json 复制代码
{
  "answer": {
    "everything": 42
  },
  "happy": true,
  "list": [
    1,
    0,
    2
  ],
  "name": "Niels",
  "nothing": null,
  "object": {
    "currency": "USD",
    "value": 42.99
  },
  "pi": 3.141
}

方式2

cpp 复制代码
int main()
{
    using json = nlohmann::json;
    json j = {
        {"pi", 3.141},
        {"happy", true},
        {"name", "Niels"},
        {"nothing", nullptr},
        {"answer", {{"everything", 42}}},
        {"list", {1, 0, 2}},
        {"object", {{"currency", "USD"}, {"value", 42.99}}}
    };

    // 转成字符串
    std::string strJSON = j.dump(2);

    std::cout << strJSON;
    return 0;
}

输出内容与方式1一样。

方式3

cpp 复制代码
int main()
{
    using json = nlohmann::json;

    json j;
    j["pi"] = 3.141;
    j["happy"] = true;
    j["name"] = "Niels";
    j["nothing"] = nullptr;

    json j_answer;
    j_answer["everything"] = 42;

    j["answer"] = j_answer;

    json j_list = json::array();
    j_list.push_back(1);
    j_list.push_back(0);
    j_list.push_back(2);

    j["list"] = j_list;

    json j_object;
    j_object["currency"] = "USD";
    j_object["value"] = 42.99;

    j["object"] = j_object;

    // 转成字符串
    std::string strJSON = j.dump(2);

    std::cout << strJSON;
    return 0;
}

输出内容与方式1一样。

2.2 解析JSON

cpp 复制代码
int main()
{
    using json = nlohmann::json;

    std::string strJSON = u8R"(
    {
        "answer": {
             "everything": 42
        },
        "happy": true,
        "list": [
            1,
            0,
            2
         ],
        "name": "Niels",
        "nothing": null,
        "object": {
            "currency": "USD",
            "value": 42.99
        },
        "pi": 3.141
    }
    )";

    auto jsonObj = json::parse(strJSON);
    std::cout << jsonObj["pi"].get<float>() << std::endl; // 3.141
    std::cout << jsonObj["pi"].get<double>() << std::endl; // 3.141
    std::cout << std::boolalpha << jsonObj["happy"].get<bool>() << std::endl; // true
    std::cout << jsonObj["name"].get<std::string>() << std::endl; // Niels
    assert(jsonObj["nothing"] == nullptr);
    std::cout << jsonObj["answer"]["everything"].get<int>() << std::endl; // 42
    std::cout << jsonObj["list"].size() << std::endl; // 3
    std::cout << jsonObj["list"][0].get<int>() << std::endl; // 1
    std::cout << jsonObj["list"][1].get<int>() << std::endl; // 0
    std::cout << jsonObj["list"][2].get<int>() << std::endl; // 2
    std::cout << jsonObj["object"]["currency"].get<std::string>() << std::endl; // USD
    std::cout << jsonObj["object"]["value"].get<float>() << std::endl; // 42.99

    // 依次输出:
    // 1
    // 0
    // 2
    for (json::iterator it = jsonObj["list"].begin(); it != jsonObj["list"].end(); ++it) {
        std::cout << *it << std::endl;
    }

    return 0;
}

3. 异常处理

当解析和生成JSON出错时,nlohmann/json会抛出异常,因此在解析和生成JSON时,需要进行异常捕获。

cpp 复制代码
int main()
{
    using json = nlohmann::json;

    std::string strJSON = u8R"(
    {
        "pi": 3.141
    }
    )";

    try {
        auto jsonObj = json::parse(strJSON);
        std::cout << jsonObj["ppp"].get<float>() << std::endl;
    }
    catch (std::exception& e) {
        std::cout << e.what() << std::endl;
    }

    return 0;
}

4. 判断成员是否存在

cpp 复制代码
int main()
{
    using json = nlohmann::json;

    std::string strJSON = u8R"(
    {
        "pi": 3.141
    }
    )";

    auto jsonObj = json::parse(strJSON);
    std::cout << std::boolalpha << jsonObj.contains("pi") << std::endl; // true
    std::cout << std::boolalpha << jsonObj.contains("ppp") << std::endl; // false

    return 0;
}

欢迎访问我的个人站点:https://jiangxueqiao.com

相关推荐
One_Blanks8 小时前
WIndows x64 ShellCode开发 第三章 x64汇编细节点
汇编·windows·网络安全·渗透测试·红队技术
C++ 老炮儿的技术栈8 小时前
分享一个安全的CString
c语言·c++·windows·git·安全·visual studio
淼淼爱喝水9 小时前
openEuler 下 Ansible 基础命令详解与实操演示2
linux·运维·windows
One_Blanks10 小时前
WIndows ShellCode开发 第四章 动态API调用
windows·网络安全·渗透测试
idolao10 小时前
RStudio 2025 + R 4.5.0 安装与配置教程 Windows版:解压+双软件安装+自定义路径+R语言关联指南
windows
Leo6553510 小时前
动态透视报表 + 查询接口 + Excel导出
开发语言·windows·python
One_Blanks14 小时前
WIndows x64 ShellCode开发 第五章 反向Shell编写
windows·网络安全·渗透测试
玖釉-14 小时前
暴力美学与极致性能:深度解析 Meshoptimizer 的 Sloppy 减面算法
c++·windows·图形渲染
dashizhi201515 小时前
服务器共享文件禁止下载、禁止拖动共享文件到本地磁盘、禁止拷贝共享文件
运维·服务器·windows
水饺编程15 小时前
第4章,[标签 Win32] :SysMets3 程序讲解02,iVertPos
c语言·c++·windows·visual studio