代码之家  ›  专栏  ›  技术社区  ›  Alon

JSON中作为值的向量(C++/nlohmann::JSON)

  •  0
  • Alon  · 技术社区  · 2 年前

    我想要这样的东西:

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

    我有一个 std::vector<std::string> 房间的名称,我想将其转换为JSON的键为“rooms”,其值为所有房间的列表。
    作为结论,
    如何转换 std::vector 将JSON数组作为值(而不是键)保存。
    谢谢你的帮助!:)

    1 回复  |  直到 2 年前
        1
  •  2
  •   Ted Lyngmo    2 年前

    您可以直接从 std::vector<std::string> 所以类似的方法会奏效:

    #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';
    }
    

    输出

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