Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector as value in JSON (C++/nlohmann::json)

I want to have something like that:

{ "rooms": [ "room1", "room2", "room3", etc ] }

I have an std::vector<std::string> of the name of the rooms, and I would like to convert it so the key of the JSON will be 'rooms', and its value will be a list of all the rooms.
For conclusion,
How to convert a std::vector to JSON array as a value (not a key).
Thanks for the helpers! :)

like image 309
Alon Avatar asked Dec 18 '25 02:12

Alon


1 Answers

You can create a Json array directly from the std::vector<std::string> so something like this will work:

#include <nlohmann/json.hpp>

#include <iostream>
#include <string>
#include <vector>

using json = nlohmann::json;

int main() {
    std::vector<std::string> rooms{
        "room1",
        "room2",
        "room3",
    };

    json j;

    // key `rooms` and create the json array from the vector:
    j["rooms"] = rooms;

    std::cout << j << '\n';
}

Output

{"rooms":["room1","room2","room3"]}
like image 112
Ted Lyngmo Avatar answered Dec 20 '25 18:12

Ted Lyngmo