我有一个带有 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/