如何从 GCS 读取 json gzip 文件并写入 table?

How to read json gzipped file from GCS and write to table?

我有一个 json 压缩的 gzip 文件 (.json.gz) 存储在 Google Cloud Storage 的存储桶中,我想在其中读取它并将其复制到 postgres table。我拥有的 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 的 table?

要读取数据,我会使用 gcsfs、Python 到 GCS 的接口:

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 相同的代码。