簡體   English   中英

如何從谷歌雲存儲桶中讀取 python 代碼中的.json 文件

[英]How to Read .json file in python code from google cloud storage bucket

我正在嘗試從存儲在谷歌雲存儲桶中的VM 實例中讀取 python 代碼中的.json文件作為dict()

我嘗試將 json 文件作為 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 我的方法正確嗎? 如果有其他可用的方法,請告訴我。

我需要類似的東西:

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

這是使用官方 Cloud Storage 庫訪問它的另一種方法:

# 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))

使用 gcsfs 連接到谷歌雲存儲桶,然后將其加載為 json。

import gcsfs
import json

fs = gcsfs.GCSFileSystem(project='your-gcp-project-name')
url = "gs://bucket_name/filename.json"
with fs.open(url, 'rb') as f:
    data=json.load(f)

此方法使用 GCS 文件系統gcsfs可用於從 Google Cloud 存儲中讀取文件。

# Reading gcs files with gcsfs
import gcsfs
import json

gcs_file_system = gcsfs.GCSFileSystem(project="gcp_project_name")
gcs_json_path = "gs://bucket_name/path/to/file.json"
with gcs_file_system.open(gcs_json_path) as f:
  json_dict = json.load(f)

此方法也適用於使用skimage存儲在 GCS 中的圖像

from skimage import io
with gcs_file_system.open(gcs_img_path) as f:
  img = io.imread(f)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM