How To Convert Python Dictionary (dict) to JSON
(And Write It To A File)
To convert a dictionary to a JSON string in Python, you can use the json module's dumps() method.
This method takes a dictionary as input and returns a JSON-formatted string.
Here is an example of how to use the dumps() method to convert a dictionary to a JSON string:
import json my_dict = { "key1": "value1", "key2": "value2", "key3": "value3" }json_string = json.dumps(my_dict)
print(json_string)
This code creates a dictionary my_dict and then uses the json.dumps() method to convert it to a JSON string. The resulting JSON string will be formatted like this:
'{"key1": "value1", "key2": "value2", "key3": "value3"}'
How to write dictionary to a file
You can also use the json.dump() method to write the JSON string to a file instead of printing it to the console.
This method takes a file object (returned from open function) as its first argument and the dictionary as its second argument.
Here is an example of how to use the json.dump() method to write a dictionary to a file:
import json my_dict = { "key1": "value1", "key2": "value2", "key3": "value3" }with open("my_file.json", "w") as f:
json.dump(my_dict, f)
This code creates a dictionary my_dict and then opens a file named my_file.json in write mode.
It then uses the json.dump() method to write my_dict to the file and automatically closes the file when it is done.
The resulting file will contain the JSON-formatted string representation of my_dict.