使用 nlohmann/json 获取 api

问题描述

我想在 c++ 中使用 api,当我搜索时,我发现 nlohmann/json 库看起来非常流行,但没有人谈论如何获取 fetch 函数提供的数组。如何从 api 获取信息作为我的 cpp 文件中的变量

解决方法

不太明白你的描述,我猜你的意思是你想得到 JSON 数组?你可以试试这个:

std::string ss= R"(
{
    "test-data":
    [
        {
            "name": "tom","age": 11
        },{
            "name": "jane","age": 12
        }
    ]
}
)";

json myjson = json::parse(ss);

auto &students = myjson["test-data"];

for(auto &student : students) {
    cout << "name=" << student["name"].get<std::string>() << endl;
}