c ++ nlohmann json-如何迭代/查找嵌套对象 [英] c++ nlohmann json - how to iterate / find a nested object

查看:1581
本文介绍了c ++ nlohmann json-如何迭代/查找嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用nlohmann :: json遍历嵌套的json.我的json对象如下:

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

我正在尝试迭代和/或查找嵌套对象.但是,似乎没有默认支持.看来我必须通过创建另一个循环来遍历每个子对象,或者为每个子对象递归调用fn.

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

和输出:

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()方法自己做?

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

推荐答案

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

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

输出为:

1
"three.one"
3.1
2

这篇关于c ++ nlohmann json-如何迭代/查找嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆