How to Read and Parse JSON files with Python
Published on Aug. 22, 2023, 12:12 p.m.
What JSON is?
JSON is short for Javascript Object Notation .A simple structure and popular for information exchange between servers and clients is JSON data.It is a simple syntax for storing data.Different data types can be different as long as they are valid.Non- acceptable types for JSON include functions, dates, and more.
Heres a JSON file looks like:
{
"name": "John",
"age": 50,
"is_married": false,
"profession": null,
"hobbies": ["traveling", "photography"]
}
In this article, we’ve learned how to read JSON files and parse such files using the read method of file objects.
How to Read JSON files .
Let’s say the JSON is stored in a user.json file .Using the open() inbuilt function in Python, we can read that file .
with open('user.json') as user_file:
file_contents = user_file.read()
print(file_contents)
# {
# "name": "John",
# "age": 50,
# "is_married": false,
# "profession": null,
# "hobbies": ["travelling", "photography"]
# }
You pass the file path to the open method which opens the file to the user_file variable.Using the read method, you can pass the text contents of the file.
File_contents now contains a stringified version.
How to Parse json.
For managing JSON files, Python has the JSON module.
One of which is the loads() method.
import json
with open('user.json') as user_file:
file_contents = user_file.read()
print(file_contents)
parsed_json = json.loads(file_contents)
# {
# 'name': 'John',
# 'age': 50,
# 'is_married': False,
# 'profession': None,
# 'hobbies': ['travelling', 'photography']
# }
Using the loads() method now has a valid dictionary.
Also notice how null from the JSON is converted to none.
How to Use json.load() to Read.
The json module also has the load method which you can use to read a file object .
import json
with open('user.json') as user_file:
parsed_json = json.load(user_file)
print(parsed_json)
# {
# 'name': 'John',
# 'age': 50,
# 'is_married': False,
# 'profession': None,
# 'hobbies': ['travelling', 'photography']
# }
Instead of using the read method of the file object and using the loads method of the json module, you can directly