【问题标题】:How to Read .json file in python code from google cloud storage bucket如何从谷歌云存储桶中读取python代码中的.json文件
【发布时间】:2021-02-10 13:12:22
【问题描述】:

我正在尝试从存储在谷歌云存储桶中的 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')

【问题讨论】:

    标签: json python-3.x google-cloud-storage


    【解决方案1】:

    这是使用官方 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))
    

    【讨论】:

      【解决方案2】:

      此方法使用 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-13
        • 2021-12-23
        相关资源
        最近更新 更多