Maxbad`Blog

nlohmann/json 使用记录

2020-05-12 · 3 min read

nlohmann库是C++解析json的库,库使用很简单,程序中使用nlohmann仅需要将json.hpp添加到工程中即可。在线帮助文档

介绍:https://blog.csdn.net/qq_26189301/article/details/108254642

抛出详细的异常

定义一下宏 JSON_DIAGNOSTICS

定义一个JSON对象:

//定义一个JSON对象
nlohmann::json ret_json = { {"code", 1}, {"msg", u8"系统开小差, 请稍后再试啊啊啊!"} };

输出内容:
{
	"code": 1,
	"msg": "系统开小差, 请稍后再试啊啊啊!"
}

// 方式2:
nlohmann::json j = R"({"name": "Judd Trump","credits": 1754500,"ranking": 1})"_json; 

打印json对象内容

j_object.dump(缩进量)

通过key删除

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';

获取值:

auto& username = req_json["username"].get<std::string>();

遍历对象

for (auto it=j.begin(); it!=j.end(); it++) {
    std::cout << "key: " << it.key() << " : " << it.value() << std::endl; 
    // it.value() 是json对象
  }
#include "json.hpp"
#include <iostream>

using json = nlohmann::json;

template<class UnaryFunction>
void recursive_iterate(const json& j, UnaryFunction f)
{
    for(auto it = j.begin(); it != j.end(); ++it)
    {
        if (it->is_structured())
        {
            recursive_iterate(*it, f);
        }
        else
        {
            f(it);
        }
    }
}

int main()
{
    json j = {{"one", 1}, {"two", 2}, {"three", {"three.one", 3.1}}};
    recursive_iterate(j, [](json::const_iterator it){
        std::cout << *it << std::endl;
    });
}

解析

nlohmann::json::parse如果是非法的json会直接丢一个异常,可以通过nlohmann::json::accept判断是否合法

#对象是否存在

// find an entry
if (o.contains("foo")) {
  // there is an entry with key "foo"
}

// or via find and an iterator
if (o.find("foo") != o.end()) {
  // there is an entry with key "foo"
}

// or simpler using count()
int foo_present = o.count("foo"); // 1
int fob_present = o.count("fob"); // 0