12

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

nullromo
  • 2,165
  • 2
  • 18
  • 39
P i
  • 29,020
  • 36
  • 159
  • 267
  • 1
    it seems you have to do that by hand iterating on xx.items() to push_back the element into the vector ( https://nlohmann.github.io/json/classnlohmann_1_1basic__json_afe3e137ace692efa08590d8df40f58dd.html#afe3e137ace692efa08590d8df40f58dd ) – bruno Jan 27 '19 at 15:48
  • 1
    or using from_json to an intermediate std::array ? not easy to read their sources (https://nlohmann.github.io/json/json_8hpp_source.html) – bruno Jan 27 '19 at 15:55

1 Answers1

24

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);
nullromo
  • 2,165
  • 2
  • 18
  • 39
P i
  • 29,020
  • 36
  • 159
  • 267