Home > database >  Iterate using iterators on nlohmann::json? Error: invalid_iterator
Iterate using iterators on nlohmann::json? Error: invalid_iterator

Time:11-26

Continuing my previous question here, Now I want to insert the keys and values present in the below json into a std::vector<std::pair<std::string, std::vector<uint64_t>>> vec;

Keys here are this strings: 12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq , 12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT

values corresponding them are list:[20964,347474, 34747],[1992,1993,109096]

This is the json which is response from query.

         j =   {
                "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq": [
                    20964,
                    347474,
                    347475
                ],
                "12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT": [
                    1992,
                    1993,
                    109096  
                ]
        }

To try first I have tried to insert only first element's key and value. It is working correctly.

 std::vector<std::pair<std::string, std::vector<uint64_t>>> vec;
  auto key = j.begin().key();
  auto value = j.begin().value();
  vec.push_back(std::make_pair(key, value));

Now I am trying this way to insert all the key values in vector

std::vector<std::pair<std::string, std::vector<uint64_t>>> vec;
  int i = 0;
  while ((j.begin()   i) != j.end()) {
    auto key = (j.begin()   i).key();
    auto value = (j.begin()   i).value();
    vec.push_back(std::make_pair(key, value));
    i  ;
  }

I am getting the error:

 [json.exception.invalid_iterator.209]
cannot use offsets with object iterators

Can someone please what is the correct way of doing this ?

CodePudding user response:

I think you're over complicating this. You can iterate over a json object the same way you would any other container using a for loop:

#include "nlohmann/json.hpp"
#include <iostream>

int main()
{
    nlohmann::json j = nlohmann::json::parse(R"({
                "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq": [
                    20964,
                    347474,
                    347475
                ],
                "12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT": [
                    1992,
                    1993,
                    109096  
                ]
        })");
    std::vector<std::pair<std::string, std::vector<uint64_t>>> vec;
    for (auto it = j.begin(); it != j.end();   it)    
    {
        vec.emplace_back(it.key(), it.value());
    }
    for (auto& it : vec)
    {
        std::cout << it.first << ": ";
        for (auto& value : it.second)
        {
            std::cout << value << ", ";
        }
        std::cout << "\n";
    }
}

If you don't care about the order of items (JSON keys are unordered anyway and nlohmann doesn't preserve the order by default) then you can do this in a one liner:

std::map<std::string, std::vector<uint64_t>> vec = j;
  • Related