We often need to save a Python dictionary as a JSON file. For this task, we can work with the Python built-in package called json
, and more specifically with the json.dump()
method. Let’s move on with an example where we will create a simple dictionary and we will save it as a json
file.
import json # create a dictionary my_dict = { 'Name': 'George', 'Surname': 'Pipis', 'Country': 'Greece', 'Company': 'Predictive Hacks', 'Year': 2023 } print(my_dict)
{'Name': 'George', 'Surname': 'Pipis', 'Country': 'Greece', 'Company': 'Predictive Hacks', 'Year': 2023}
Now, let’s save the my_dict
as a json file called my_json.json
.
with open("my_json.json", "w") as fp: json.dump(my_dict, fp)
As we can see, a new file called my_json.json
has been created under the working directory.
Finally, if we want to load the json file we can work as follows:
with open('my_json.json', 'r') as fp: data = json.load(fp) print(data)
{'Name': 'George', 'Surname': 'Pipis', 'Country': 'Greece', 'Company': 'Predictive Hacks', 'Year': 2023}
Note that the data
object is a dictionary.
type(data)
dict