我正在尝试使用 nlohmann::json 迭代嵌套的 json。我的 json 对象如下:
{
"one": 1,
"two": 2
"three": {
"three.one": 3.1
},
}
我正在尝试迭代和/或查找嵌套对象。但是,似乎没有对它的默认支持。看起来我必须通过创建另一个循环来迭代每个子对象,或者为每个子对象递归调用 fn。
我的以下代码及其结果表明,只有顶级迭代是可能的。
void findNPrintKey (json src, const std::string& key) {
auto result = src.find(key);
if (result != src.end()) {
std::cout << "Entry found for : " << result.key() << std::endl;
} else {
std::cout << "Entry not found for : " << key << std::endl ;
}
}
void enumerate () {
json j = json::parse("{ \"one\" : 1 , \"two\" : 2, \"three\" : { \"three.one\" : 3.1 } } ");
//std::cout << j.dump(4) << std::endl;
// Enumerate all keys (including sub-keys -- not working)
for (auto it=j.begin(); it!=j.end(); it++) {
std::cout << "key: " << it.key() << " : " << it.value() << std::endl;
}
// find a top-level key
findNPrintKey(j, "one");
// find a nested key
findNPrintKey(j, "three.one");
}
int main(int argc, char** argv) {
enumerate();
return 0;
}
和输出:
ravindrnathsMBP:utils ravindranath$ ./a.out
key: one : 1
key: three : {"three.one":3.1}
key: two : 2
Entry found for : one
Entry not found for : three.one
那么,是否有可用的递归迭代,或者我们必须自己做这个,使用 is_object() 方法?