Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use nlohmann json to unpack list of integers to a std::vector<int>

I'm using https://github.com/nlohmann/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, 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

like image 979
P i Avatar asked Jan 27 '19 15:01

P i


1 Answers

meow

So 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++ var-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);
like image 118
P i Avatar answered Oct 16 '22 01:10

P i