gpt4 book ai didi

c++ - 使用 rapidjson 读取子对象 vector

转载 作者:行者123 更新时间:2023-11-28 04:06:43 24 4
gpt4 key购买 nike

这是我的 json:

{
"data": {
"text": "hey stackoverflow",
"array_1": [
["hello", "world", 11, 14]
]
},
}

我已经设法提取了 text像这样的属性:

代码:

document.Parse(request_body);

auto& data = document["data"];

std::string text = data["text"].GetString();
printf("text: %s\n", text.c_str());

输出:

text: hey stackoverflow

现在我需要提取 array_1作为 std::vector<std::vector<std::any>> .

我想,要拥有这样的数据类型,我将不得不遍历 data["array_1"]使用 rapidjson 的类型来填充 vector 。

问题是,即使尝试复制我在互联网上看到的内容,我仍然无法读取 data["array_1"] 中的值.

代码:

auto& array_1 = data["array_1"];
static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };

for (rapidjson::Value::ConstValueIterator itr = array_1.Begin(); itr != array_1.End(); ++itr){
printf("item\n");
for (rapidjson::Value::ConstValueIterator itr2 = itr->Begin(); itr2 != itr->End(); ++itr2){
printf("Type is %s\n", kTypeNames[itr->GetType()]);
}
}

输出:

item
Type is Array
Type is Array
Type is Array
Type is Array

但我需要:

item
Type is String
Type is String
Type is Number
Type is Number

编辑

我调用 GetType在错误的迭代器上..

感谢帮助

最佳答案

    printf("Type is %s\n", kTypeNames[itr2->GetType()]);

不是

    printf("Type is %s\n", kTypeNames[itr->GetType()]);

您正在打印 item 的类型,也就是 ["hello", "world", 11, 14],而不是 [ "hello", "world", 11, 14] 重复。

或者:

for (auto&& item : array_1.GetArray()) {
printf("item\n");
for (auto&& elem : item.GetArray()){
printf("Type is %s\n", kTypeNames[elem.GetType()]);
}
}

去除一些迭代噪音。 (需要 和 rapidJson v1.1.0)

关于c++ - 使用 rapidjson 读取子对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58595032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com