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、これに自分自身を行う必要がありますか?