How to read a JSON file in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
You will at some point encounter JSON data.
It is the most widely used format for communication and transmission.
There are two ways to read a JSON file that I use most of the time.
It really depends on the structure of the file.
Reading JSON with the JSON library
When I encounter a JSON file that looks like this and is a straight dictionary, I use the JSON library like so
{
"firstname" : "Brice",
"lastname" : "Doe",
"age" : 20,
"has_siblings" : True,
"favorite_quote" : """
The world as we have created it is a process of our thinking.
It cannot be changed without changing our thinking. Albert Einstein
"""
}
and
import json # We import the JSON library
with open("path/to/file.json", "r") as file:
data = json.load(file) # we load the file to the data variable
print(data) # We check the data we have is alright
Reading JSON with pandas library
You might encounter other JSON-like formats, like a JSON file containing a list of records. This is often the case when dealing with APIs.
Such file would look like this :
[
{"firstname":"George","lastname":"Dubois"},
{"firstname":"Aman","lastname":"Van Hein"},
{"firstname":"Dennis","lastname":"Washington"},
{"firstname":"John","lastname":"Doe"},
{"firstname":"Foe","lastname":"Less"}
]
Then I would read it like so
import pandas as pd # we import the pandas library to read it as dataframe
df = pd.read_json("path/to/file_2.json") # We read the file as dataframe
print(df) # We print the dataframe object
Here you are! You are now an expert at reading JSON files.
This can also be applied when you deal with APIs data !
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚