1

What is the best way to upload a JSON string (created in memory, not read from a file) to azure blob storage using the python sdk?

I understand from the docs at https://pypi.org/project/azure-storage-blob/ that I can upload a file to azure blob storage by doing the following.

from azure.storage.blob import BlobClient

blob = BlobClient.from_connection_string(conn_str="<connection_string>", container_name="my_container", blob_name="my_blob")

with open("./SampleSource.txt", "rb") as data:
    blob.upload_blob(data)

but I am struggling to find any examples where a string is uploaded directly.

Is it possible to upload a string directly? If so, how is it done in python?

Thanks.

2 Answers 2

6

You can simply pass the string to upload_blob method. No need to do anything special.

For example, code below should work just fine.

blob = BlobClient.from_connection_string(conn_str="<connection_string>", container_name="my_container", blob_name="my_blob")

data = "This is a test"
blob.upload_blob(data)
Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me - not a part of the original question but the data uploaded has to be a string. I was trying to do it with a dictionary and it wasn't working so just use json.dumps to get it into a string.
2

If you're trying to upload a json object and not a json formatted string, you'll first need to turn the json obj into a string so that BlobClient can upload. e.g. if getting a json obj from an api...

response = requests.get("<some endpoint>")
blob = BlobClient.from_connection_string(conn_str="<connection_string>", container_name="my_container", blob_name="my_blob")

data = json.dumps(response.json())
blob.upload_blob(data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.