Home > front end >  Vector as value in JSON (C /nlohmann::json)
Vector as value in JSON (C /nlohmann::json)

Time:05-09

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! :)

CodePudding user response:

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 <std::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"]}
  • Related