我正在使用 nlohmann/json 库在 cpp 中使用 json。我有一个 Json::Value 对象,我想通过在不知道键的情况下探索键来浏览我的 json 数据。我遇到了文档,但只找到了object["mySuperKey"]
探索数据的方法,这意味着知道现有的密钥。
你能给我一些建议吗?
谢谢。
我正在使用 nlohmann/json 库在 cpp 中使用 json。我有一个 Json::Value 对象,我想通过在不知道键的情况下探索键来浏览我的 json 数据。我遇到了文档,但只找到了object["mySuperKey"]
探索数据的方法,这意味着知道现有的密钥。
你能给我一些建议吗?
谢谢。
在创建一个 json 对象之后 - 有可以迭代的类型。在这个nlohmann::json
实现中,您与基本容器(json::object
, json::array
)进行交互,它们都有可以轻松检索或打印的键。
这是一个小例子,它实现了一个函数来递归(或不)遍历 json 对象并打印键和值类型。
示例代码:
#include <iostream>
#include <vector>
#include "json3.6.1.hpp"
void printObjectkeys(const nlohmann::json& jsonObject, bool recursive, int ident) {
if (jsonObject.is_object() || jsonObject.is_array()) {
for (auto &it : jsonObject.items()) {
std::cout << std::string(ident, ' ')
<< it.key() << " -> "
<< it.value().type_name() << std::endl;
if (recursive && (it.value().is_object() || it.value().is_array()))
printObjectkeys(it.value(), recursive, ident + 4);
}
}
}
int main()
{
//Create the JSON object:
nlohmann::json jsonObject = R"(
{
"name" : "XYZ",
"active" : true,
"id" : "4509237",
"origin" : null,
"user" : { "uname" : "bob", "uhight" : 1.84 },
"Tags" :[
{"tag": "Default", "id": 71},
{"tag": "MC16", "id": 21},
{"tag": "Default", "id": 11},
{"tag": "MC18", "id": 10}
],
"Type" : "TxnData"
}
)"_json;
std::cout << std::endl << std::endl << "Read Object key, not recursive :" << std::endl;
printObjectkeys(jsonObject, false, 1);
std::cout << std::endl << std::endl << "Read Object key, recursive :" << std::endl;
printObjectkeys(jsonObject, true, 1);
return 0;
}