python - 如何从 GCS 读取 json gzip 文件并写入表?

标签 python json postgresql google-cloud-storage gzip

我有一个带有 gzip 文件 (.json.gz) 的 json 压缩存储在 Google Cloud Storage 的存储桶中,我想在其中读取它并将其复制到 postgres 表中。我拥有的 json.gz 文件只是一个没有嵌套对象的 json 文件,如下所示:

[{
“date”: “2019-03-10T07:00:00.000Z”,
“type”: “chair”,
“total”: 250.0,
"payment": "cash"
},{
“date”: “2019-03-10T07:00:00.000Z”,
“type”: “shirt”,
“total”: 100.0,
"payment": "credit card"
},{
.
.
}]

以前我用 csv 文件做了类似的工作,我可以在其中使用 download_as_string 函数并将其存储在变量中并使用 StringIO 将该变量转换为类文件对象并将 copy_expert() 函数用于查询 ( this link )。

那么,如何在 GCS 中读取 json.gz 文件并使用 Python 将其写入表?

最佳答案

要读取数据,我会选择 gcsfs ,GCS 的 Python 接口(interface):

import gcsfs
import gzip
import json

fs = gcsfs.GCSFileSystem(project='my-project')
with fs.open('bucket/path.json.gz') as f:
    gz = gzip.GzipFile(fileobj=f) 
    file_as_string = gz.read()
    your_json = json.loads(file_as_string)

现在您有了 json,您可以使用与 csv 相同的代码。

关于python - 如何从 GCS 读取 json gzip 文件并写入表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56208439/

相关文章:

python - 在 GitPython 中获取第一次提交的差异细节

java - 有没有用java序列化的python反序列化的库

java - JSONArray 在编码时丢失

javascript - ajax每次点击 "load more"按钮加载2条记录

json - JPA (EclipseLink) 自定义类型是否可行?

asp.net-mvc - 使用现有 Postgres 数据库访问 MVC3 数据库

performance - 在 PostgreSQL 中填充数据库

python - 逐步创建异步任务并等待所有任务完成

python - 修复 Pandas 中的一列 RPT 文件

java - SerializationException 在 Android Studio 中为 LibGDX uiskin 读取 JSON 文件时出错