如何从谷歌云存储桶中读取python代码中的.json文件 [英] How to Read .json file in python code from google cloud storage bucket

查看:124
本文介绍了如何从谷歌云存储桶中读取python代码中的.json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从存储在Google云存储桶中的 VM实例中的python代码中以dict()的形式读取.json文件.

I'm trying to read a .json file as dict() in a python code from VM instance stored in google cloud storage bucket.

我尝试将json文件读取为blob:

I tried reading json file as blob:

client = storage.Client()
bucket = client.get_bucket('bucket-id-here')
blob = bucket.get_blob('remote/path/to/file.json')
str_json = blob.download_as_string()

但是我无法解码str_json.我的方法正确吗?如果有其他可用的方法,请告诉我.

But I'm unable to decode the str_json. Is my approach correct? if any other approach available please let me know.

我需要类似的东西:

# Method to load json
dict = load_json(gcs_path='gs://bucket_name/filename.json')

推荐答案

以下是使用官方云存储库进行访问的另一种方法:

Here is an alternative way to reach it using the official Cloud Storage library:

# Import the Google Cloud client library and JSON library
from google.cloud import storage
import json

# Instantiate a Google Cloud Storage client and specify required bucket and file
storage_client = storage.Client()
bucket = storage_client.get_bucket('bucket_name')
blob = bucket.blob('filename.json')

# Download the contents of the blob as a string and then parse it using json.loads() method
data = json.loads(blob.download_as_string(client=None))

这篇关于如何从谷歌云存储桶中读取python代码中的.json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆