We will use json.dums() function to convert to json from python dictionary and json.loads() to convert from json to python dictionary.
In this example code we used flower details data in python dictionary and converted it to json.
import json
# flowers in python dictionary
flowers = {
"rose": {
"scientific_name": "Rosa",
"grows_in": ["gardens", "wild"],
"colors": ["red", "pink", "white"]
},
"sunflower": {
"scientific_name": "Helianthus annuus",
"grows_in": ["fields", "gardens"],
"colors": ["yellow"]
}
}
# Converting Python dictionary to JSON
flowers_json = json.dumps(flowers)
# converted to json
print(flowers_json)
# we can add indent to make it more readable
flowers_json = json.dumps(flowers, indent=4)
print(flowers_json)
# Now convert json to python dictionary
#fowers_json is alreay in json
flowers_dict = json.loads(flowers_json)
#converted to python dictionary
print(flowers_dict)
Exporting Python Dictionaries to JSON Files
we can also export this python dictionary data to json
import json
# flowers in python dictionary
flowers = {
"rose": {
"scientific_name": "Rosa",
"grows_in": ["gardens", "wild"],
"colors": ["red", "pink", "white"]
},
"sunflower": {
"scientific_name": "Helianthus annuus",
"grows_in": ["fields", "gardens"],
"colors": ["yellow"]
}
}
# Converting Python dictionary to JSON
flowers_json = json.dumps(flowers)
# Exporting Python dictionary to a JSON file
with open("flowers.json", "w") as json_file:
json.dump(flowers, json_file, indent=4)
Loading JSON Data from Files into Python Dictionaries
# Loading JSON data from a file into Python dictionary
import json
with open("flowers.json", "r") as json_file:
#convert to python dictionary with json.load()
loaded_flowers_dictionary = json.load(json_file)
print(loaded_flowers_dictionary)