我正在Google云平台上开发一个原型,为此我使用了云存储、appengine和bigquery。
现在,其中一项任务是每天从google云存储向bigquery加载一个文件,我在Appengine上使用Cron任务
问题是bigquery期望数据是NDJSON格式(新的行分隔为json),而我的源文件则是普通的JSON格式。
目前,我将该文件下载到我的笔记本电脑,并将其转换为NDJSOn,然后上传到bigquery,但是如何在google上编程呢?我希望有一些可用的东西,我可以使用,因为我不想从头开始写。
发布于 2016-08-11 13:59:58
可能对其他人有用。我就是这样做的,但如果有更好或更容易的方法,请告诉我。需要下载云存储java和依赖项(http和oauth ):https://developers.google.com/api-client-library/java/apis/
需要像jackson一样下载JSON解析器。
步骤
1>使用java云存储API将json文件作为inputstream读取。
Storage.Objects.Get getObject = client.objects().get("shiladityabucket", "abc.json");
InputStream input = getObject.executeMediaAsInputStream();2>转换为Java数组(在我的示例中,json文件有多个记录)。如果是一条记录,就不需要数组了。
ObjectMapper mapper = new ObjectMapper();
BillingInfo[] infoArr = mapper.readValue(input, BillingInfo[].class);3>创建一个上传到云存储的StorageObject
StorageObject objectMetadata = new StorageObject()
// Set the destination object name
.setName("abc.json")
// Set the access control list to publicly read-only
.setAcl(Arrays.asList(
new ObjectAccessControl().setEntity("allUsers").setRole("READER"))); 4>对数组中的对象进行迭代,并将它们转换为json。为ndjson追加新行。
for (BillingInfo info:infoArr) {
jSonString += mapper.writeValueAsString(info);
jSonString += "\n";
} 5>使用云存储java创建要插入的Inputstream
InputStream is = new ByteArrayInputStream(jSonString.getBytes());
InputStreamContent contentStream = new InputStreamContent(null, is);6>上传文件
Storage.Objects.Insert insertRequest = client.objects().insert(
"shiladitya001", objectMetadata, contentStream);
insertRequest.execute(); https://stackoverflow.com/questions/38848661
复制相似问题