2017-08-29 1141 views
1

我想使用nlohmann :: json遍历嵌套的json。我的json对象如下:C++ nlohmann 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()方法?

回答

2

确实,迭代不会递归,并且此(还)没有库函数。怎么样:

#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; 
    }); 
} 

输出是:

1 
"three.one" 
3.1 
2