【问题标题】:How to read json gzipped file from GCS and write to table?如何从 GCS 读取 json gzipped 文件并写入表?
【发布时间】:2019-10-06 02:04:07
【问题描述】:

我有一个带有 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 将其写入表中?

【问题讨论】:

    标签: python json postgresql google-cloud-storage gzip


    【解决方案1】:

    要读取数据,我会使用gcsfs,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 相同的代码。

    【讨论】:

    • 感谢您的回答。顺便说一句,有没有其他方法可以使用官方的谷歌云客户端库,比如link,而不是 gcsfs
    • @Jamiewp 当然,这个虽然是 IMO 最 Pythonic。如果您的问题得到解决,请接受答案,如果您觉得慷慨,请点赞:)。
    • 目前我还没有尝试,明天会尝试
    • 我试过你的代码和print(g)外面,它只显示<gzip GCSFile bucket/testjson.json.gz 0x7f2c8c29b780>
    • 我使用 read() 和 json.loads() 进行了修改,并且能够打印出来,但是尝试插入数据时出错了,哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 2020-10-28
    • 2021-04-30
    • 1970-01-01
    • 2018-02-27
    • 2019-01-20
    • 1970-01-01
    相关资源
    最近更新 更多