python-3.xgoogle-cloud-platformgoogle-cloud-storageblobstore

Download blob object as a string instead of saving it as a file and then read it


Say I have a storage at Google containing a blob_file

{"name":"my name",
"number:"my number"
}

is there a way to download this file and return the download as a plain string instead of saving it as a file e.g

import json
from google.cloud import storage

downloaded_json = storage.blob.some_function(bucket_name="mybucket",blob_file="blob_file") #Gets the context of "blob_file" as a string

print(downloaded_json)
#'{"name":"my name",
#"number:"my number"
#}'
name_dict = json.loads("downloaded_json") #Convert it to a dictionary such that it can be used

print(name_dict["name"])
#"my name"

I am aware that I can download the file, read the file, delete the file - but it is to avoid this and it seems like, you can do so in Java


Solution

  • You can use download_as_text function that is documented in the Google Cloud Storage client library here