I'm using nlohman::json.
It's awesome, but is there any way to unpack:
{
"my_list" : [1,2,3]
}
into a std:vector<int>
?
I can't find any mention in the docs, and std::vector<int> v = j["my_list"];
fails, as does j["my_list"].get<std::vector<int>>()
.
Crosslinking to https://github.com/nlohmann/json/issues/1460
Actually it does work. I had not isolated a test case, and my JSON string was malformed.
So,
json J(json_string);
J["my_list"].get<std::vector<int>>()
does work.
In my case I make sure my C++ variable names match the JSON keys, so I can simply use the macro:
#define EXTRACT(x) x = J[#x].get< decltype(x) >()
int foo;
std::vector<float> bar;
EXTRACT(foo);
EXTRACT(bar);
Or better: use get_to()
since 3.3.0 to deduce the type directly. Reference
Live demo: https://godbolt.org/z/YWPdrvd7c
#include <vector>
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main(){
json j = json::parse(R"({"my_list" : [1,2,3]})");
std::cout << "json" << j << "\n";
std::vector<int> v;
j["my_list"].get_to(v);
std::cout << "items: ";
for(auto item:v){
std::cout << item << ", ";
}
}