This tutorial demonstrates how to read and write JSON files in Python. This can be very useful to store data from a Python dict.
Why Should You Use a JSON file?
JSON gained some popularity in the past decade because it is very easy to encode structured information and for being able to describe any form od data such as a Python Dictionary. In Bioinformatics, many times a set of samples has some metadata file associated with it, and a JSON file would be a great way to represent this structured type of information.
Read a JSON File
First and foremost, please consider the following JSON which represents keys as city names and values and the country where the city below.
{
"San Diego": "USA",
"San Francisco": "USA",
"Shanghai": "China",
"Tokyo": "Japan"
}
Next, using the native library json in python, we can easily read this JSON file into a Python dict by using the method json load and passing the file you want to read. See below.
import json
with open("test.json", "r") as read_file:
data = json.load(read_file)
print(data)
print(type(data))
which should print
{'San Diego': 'USA', 'San Francisco': 'USA', 'Shanghai': 'China', 'Tokyo': 'Japan'}
<class 'dict'>
Write a JSON File
Last but not least, using the json library, we can easily write a dict into a JSON file by using the method json dump which requires passing as parameters a dict and the json object. See below.
import json
data = {'San Diego': 'USA', 'San Francisco': 'USA', 'Shanghai': 'China', 'Tokyo': 'Japan'}
with open("test_output.json", "w") as json_object:
data = json.dump(data, json_object)
where “test_output.json” contains
{"San Diego": "USA", "San Francisco": "USA", "Shanghai": "China", "Tokyo": "Japan"}
More Resources
Here are three of my favorite Python Books in case you want to learn more about it.
- Python Cookbook, Third Edition by David Beazley and Brian K. Jones
- Learning Python, 5th Edition Fifth Edition by Mark Lutz
- Python Pocket Reference: Python In Your Pocket by Mark Lutz