开源nlohmann json解析库详解

nlohmann库是C++解析json的库,库使用很简单。环境使用linux+kdevelop即可,程序中使用nlohmann仅需要将json.hpp添加到工程中即可。

介绍一下相关函数的使用。

json j_object = {{"one", 1}, {"two", 2}};
查找key:

可以用三种方式  find/at/下标

1.find接口用的是迭代器,通过判断是否等于end()来判断键值是否存在

    // call find
    // print values
    std::cout << std::boolalpha;
    std::cout << "\"two\" was found: " << (it_two != j_object.end()) << '\n';

    auto it_two = j_object.find("two");

2.使用at()接口会抛出异常,需要添加异常处理

  try
    {
        // calling at() for a non-existing key
        json j = {{"foo", "bar"}};
        json k = j.at("non-existing");
    }
    catch (json::exception& e)
    {
        // output exception information
        std::cout << "message: " << e.what() << '\n'
                  << "exception id: " << e.id << std::endl;
    }
打印结果
message: [json.exception.out_of_range.403] key 'non-existing' not found
exception id: 403

3.通过下标来访问

j_object["two"]=2

打印json对象内容:

j_object.dump(缩进量)

删除:

通过key删除

   // call erase
    auto count_one = j_object.erase("one");

通过索引删除

    // create a JSON array
    json j_array = {0, 1, 2, 3, 4, 5};

    // call erase
    j_array.erase(2);

    // print values
    std::cout << j_array << '\n';

结果

[1,2,8,16]

通过迭代器删除

j_array.erase(j_array.begin() + 2);


nlohmann::json是一个开源的C++,用于解析和处理JSON数据。它提供了简单易用的API,可以方便地将JSON数据解析为C++对象,并且可以轻松地将C++对象转换为JSON格式。 要使用nlohmann::json解析文件,首先需要包含头文件`#include <nlohmann/json.hpp>`。然后,可以使用`nlohmann::json`类型的对象来表示JSON数据,并使用该对象的成员函数来解析文件。 以下是解析文件的基本步骤: 1. 打开文件并读取JSON数据。 2. 使用`nlohmann::json`对象来解析JSON数据。可以使用`json::parse()`函数将JSON字符串解析为`nlohmann::json`对象。 3. 使用`nlohmann::json`对象的成员函数来访问和处理JSON数据。 下面是一个简单的示例代码,演示了如何使用nlohmann::json解析文件: ```cpp #include <iostream> #include <fstream> #include <nlohmann/json.hpp> int main() { // 打开文件并读取JSON数据 std::ifstream file("data.json"); std::string jsonData((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); // 使用nlohmann::json对象解析JSON数据 nlohmann::json json = nlohmann::json::parse(jsonData); // 访问和处理JSON数据 std::string name = json["name"]; int age = json["age"]; // 输出解析结果 std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; return 0; } ``` 请注意,上述示例代码假设文件名为"data.json",并且文件中包含以下JSON数据: ```json { "name": "John", "age": 25 } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新手老王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值