c ++ nlohmann json - 如何迭代/查找嵌套对象

Mop*_*ath 4 c++ json nlohmann-json

我试图使用nlohmann :: json迭代嵌套的json.我的json对象如下:

{
    "one": 1,
    "two": 2
    "three": {
        "three.one": 3.1
    },
}
Run Code Online (Sandbox Code Playgroud)

我试图迭代和/或找到嵌套对象.但是,它似乎没有默认支持.看起来我必须通过创建另一个循环遍历每个子对象,或者为每个子对象递归调用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;
}
Run Code Online (Sandbox Code Playgroud)

和输出:

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
Run Code Online (Sandbox Code Playgroud)

那么,是否有可用的递归迭代,或者我们是否必须使用is_object()方法自行完成?

Nie*_*ann 9

实际上,迭代不会递归,并且没有库函数(尚未).关于什么:

#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;
    });
}
Run Code Online (Sandbox Code Playgroud)

输出是:

1
"three.one"
3.1
2
Run Code Online (Sandbox Code Playgroud)

  • 您可能想要尝试[`items()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_afe3e137ace692efa08590d8df40f58dd.html#afe3e137ace692efa08590d8df40f58dd)函数。 (2认同)