使用 C++ 和 Jsoncpp 解析 AWS S3 中的 json 文件
Parse json file from AWS S3 with C++ and Jsoncpp
我有这个C++函数,可以使用 AWS 开发工具包将 S3 文件下载为 istreams,C++:
std::istream& s3read(std::string bucket, std::string key) {
Aws::Client::ClientConfiguration aws_conf;
aws_conf.region = Aws::Environment::GetEnv("AWS_REGION");
aws_conf.caFile = "/etc/pki/tls/certs/ca-bundle.crt";
Aws::S3::S3Client s3_client(aws_conf);
Aws::S3::Model::GetObjectRequest object_request;
object_request.WithBucket(bucket.c_str()).WithKey(key.c_str());
auto get_object_outcome = s3_client.GetObject(object_request);
if (get_object_outcome.IsSuccess()) {
std::istream& res = get_object_outcome.GetResult().GetBody();
return res;
} else {
...
};
};
我从main调用它.cpp并尝试使用Jsoncpp解析它:
std::istream& stream = s3read(bucket, key);
Json::Value json;
Json::Reader reader;
reader.parse(stream, json);
但是,我不断遇到分段错误。为什么?
我认为问题在于reader.parse需要二进制数据,而istream不需要。但是,如果我是对的,我如何将流解析为二进制?
您遇到的问题是经典地返回对临时的引用
您可以稍微重新设计代码以避免这种情况。例如:
static Json::Value parse_json(std::istream& src) {
Json::Value ret;
Json::Reader reader;
reader.parse(src, ret);
return ret;
}
// Aws::String is actually same thing to std::string except the allocator
// in case of Android, otherwise this is std::string as it is.
// You can use function like s3read("foo","bar");
Json::Value s3read_json(const Aws::String& bucket,const Aws::String& key) {
static constexpr const char *FILE_NAME = "/etc/pki/tls/certs/ca-bundle.crt";
Aws::Client::ClientConfiguration aws_conf;
aws_conf.region = Aws::Environment::GetEnv("AWS_REGION");
aws_conf.caFile = FILE_NAME;
Aws::S3::S3Client s3_client(aws_conf);
Aws::S3::Model::GetObjectRequest object_request;
object_request.WithBucket( bucket ).WithKey( key );
auto object_outcome = s3_client.GetObject(object_request);
if (object_outcome.IsSuccess()) {
auto result = object_outcome.GetResult();
// destructor of object_outcome is not yet called
return parse_json( result.GetBody() );
} else {
...
// throw std::runtime_error("S3 connection failed");
};
};
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 如何使用 AWS C++ 开发工具包在给定的开始和结束日期范围内列出 S3 中的文件
- 如何将图像的字节数组(取自 s3)转换为 C++ 或 C 中的图像/图像对象
- 使用 C++ 和 Jsoncpp 解析 AWS S3 中的 json 文件