Python Dictionary to Blob Storage

If you are working with Python and want to save a dictionary to Azure blob storage as json, then the below blog is for you.

We need to follow the below steps in order to achieve this:

  1. Convert the dictionary to a json string
  2. Save the json string to a blob storage location.

Please refer to the code below.

import json

# Define a Python dictionary
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert the dictionary to a JSON string
json_string = json.dumps(data)

# Print the JSON string
print(json_string)

# Specify the output file path
output_file_path = "/path/to/output.json"

# Open the file for writing with proper formatting
with open(output_file_path, "w") as output_file:
    # Write the JSON string to the file, ensuring each object is on a separate line
    output_file.write(json_string)

print("JSON string has been written to the file with proper formatting.")

In this code, the JSON string is formatted with line breaks and indentation for readability. When you open the file in write mode and write the JSON string, it will be saved with the same formatting, with each JSON object on a separate line.

Make sure to replace "/path/to/output.json" with the actual file path where you want to save the JSON string.