Python 如何从GCS读取json Gzip文件并写入表

Python 如何从GCS读取json Gzip文件并写入表,python,json,postgresql,google-cloud-storage,gzipfile,Python,Json,Postgresql,Google Cloud Storage,Gzipfile,我有一个json压缩文件,其中包含gzip文件.json.gz,存储在Google云存储的bucket中,我想在其中读取它并将其复制到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”, “ty

我有一个json压缩文件,其中包含gzip文件.json.gz,存储在Google云存储的bucket中,我想在其中读取它并将其复制到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函数进行查询

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


感谢您阅读GCS Python接口中的数据:

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

谢谢您的回答。顺便问一下,有没有其他方法可以像这样使用官方的谷歌云客户端库而不是gcsfs@Jamiewp当然,这是我最喜欢的。如果你的问题得到解决,请接受答案,如果你觉得慷慨,请投票:。目前我还没有尝试,但明天会尝试。我尝试了你的代码和外部打印,结果显示只有我用read和json.loads进行了修改,可以打印出来,但我在尝试插入数据时出错。哈哈