C++ - 将 JSON 或数组从中转换为 vector

标签 c++ json nlohmann-json

我正在使用 https://github.com/nlohmann/json将 JSON 文件加载到我的程序中。
此刻,我正在加载它:

json jsonFile;
ifstream ifs("data/test.json");
ifs >> jsonFile;

// create JSON from stream
json j_complete(jsonFile);

我可以通过以下方式访问它:

jsonFile["data"][X][Y] // X, Y are indexes

但我想从中创建 vector - 我该怎么做?
这是此文件的示例:

{
    "cols": [
        "id",
        "title",
        "quantity",
        "price"
    ],
    "data": [
        [
            12,
            "Guzman",
            6,
            "6.31"
        ],
        [
            2,
            "..",
            5,
            "4.34"
        ],
        [
            3,
            "Goldeniererere",
            14,
            "4.15"
        ]
    ]
}

最佳答案

json 解析器已重载 [] 运算符以接受 JSON 数组的整数。所以它的访问方式与 vector 相同,但底层数据结构没有太多共同点。所以你需要把它推回到一个 std:::vector 中。如果您想在其他地方使用数据,您还需要将字段从 JSON 转换为更像 C++ 的东西。像 {int id, std::string title, int quantity, float price} 之类的东西;

然后你将把它作为内存中结构的平面 C++ 列表,上面有一个薄的 std::vector 包装器。

关于C++ - 将 JSON 或数组从中转换为 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40064212/

相关文章:

c++ - C++ 中未对齐访问的正确性

c++ - 是否可以在不影响其他行的情况下更改编辑控件的字体?

json - 如何根据响应查询Elasticsearch

javascript - NG-repeat - 通过具有不同值的对象常量属性过滤掉

c++ - 将 json 文件转换为 json 对象会打乱对象的顺序

c++ - typedef decltype 函数指针未返回正确的输出(cout)

c++ - 使在流上模板化的类同时处理 std::cout 和 std::ofstream

java - Spring MVC : How to correctly create the entity for following JSON response

c++ - 如何在 nlohmann::json 文件 C++ 中删除项目内的项目

c++ - 你如何从 nlohmann json 中的字符串中获取 JSON 对象?