c++ 使用 nlohmann json

创建日期: 2024-03-11 18:04 | 作者: 风波 | 浏览次数: 13 | 分类: C++

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

1. clone 项目

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

或者

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

clone 的文件比较大,100M以上

2. 解析 JSON

2.1 从文件解析

#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;

try {
    std::ifstream f("example.json");
    json data = json::parse(f);
    std::string dbname = d.value("name", ""); //获取值,可以指定默认值
} catch (const nlohmann::json::exception& e) {
    std::cout << e.what() << std::endl;
}

2.2 从 string 解析

std::string js = "{}";
auto j = nlohmann::json.parse(js);

3. 创建 JSON

#include <sstream>

int a() {
{
    nlohmann::json j = {
        {"code", 200},
        {"result", {{"name", dbname}}}
    };
    std::stringstream ss;
    ss << j;
    std:cout << ss.str();
}

4. 类型判断

// other stuff
j.size();     // 4 entries
j.empty();    // false
j.type();     // json::value_t::array
j.clear();    // the array is empty again

// convenience type checkers
j.is_null();
j.is_boolean();
j.is_number();
j.is_object();
j.is_array();
j.is_string();

5. 获取字符串的值

来源:https://github.com/nlohmann/json/issues/1061

json js = {
    {"a", "b"},
};

json b = js["a"]; // 此时 b 是一个字符串类型的 json, b.is_string()

std::string bv = b.get<std::string>(); // 获取 b 的字符串值
13 浏览
9 爬虫
0 评论