c++ nlohmann json - how to iterate / find a nested object

﹥>﹥吖頭↗ 提交于 2019-12-12 11:46:20

问题


I am trying to iterate over a nested json, using nlohmann::json. My json object is below:

{
    "one": 1,
    "two": 2
    "three": {
        "three.one": 3.1
    },
}

I am trying to iterate and /or find nested objects. But, it seems there is no default support for it. It looks like I have to iterate over each sub-object by creating another loop, or call the fn recursively for every sub-object.

My following piece of code, and its result indicate, that only top level iteration possible.

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

and the output:

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

So, is there a recursive iteration available, or do we have to do this ourselves, using is_object() method?


回答1:


Indeed, iteration does not recurse and there is no library function for this (yet). What about:

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

The output is:

1
"three.one"
3.1
2


来源:https://stackoverflow.com/questions/45934851/c-nlohmann-json-how-to-iterate-find-a-nested-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!