[英]Iterate using iterators on nlohmann::json? Error: invalid_iterator
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;
在这里继续我之前的问题,现在我想将下面 json 中存在的键和值插入std::vector<std::pair<std::string, std::vector<uint64_t>>> vec;
Keys here are this strings: 12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq
, 12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT
这里的键是这个字符串: 12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq
, 12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT
values corresponding them are list: [20964,347474, 34747]
, [1992,1993,109096]
它们对应的值是列表: [20964,347474, 34747]
, [1992,1993,109096]
This is the json which is response from query.这是来自查询的响应 json。
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?有人可以请这样做的正确方法是什么?
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:您可以迭代json
object ,就像使用for
循环的任何其他容器一样:
#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:如果您不关心项目的顺序(无论如何 JSON 键都是无序的并且nlohmann 默认情况下不保留顺序)那么您可以在一个班轮中执行此操作:
std::map<std::string, std::vector<uint64_t>> vec = j;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.