c++jsonlistunpacknlohmann-json

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


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


Solution

  • 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);