Working with JSON in Python
Learn how to encode Python data as JSON, decode JSON text, and work with JSON files.
01
What Is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight text format commonly used to exchange structured data between applications and APIs.
Example JSON
{"name": "Ali", "score": 92, "active": true}02
The json Module
Python includes the built-in json module, so no package installation is required.
Import JSON
import json03
Python to JSON with dumps()
Use json.dumps() to convert a Python object into a JSON string.
Serialize data
import json
student = {"name": "Ali", "score": 92}
text = json.dumps(student, indent=2)
print(text)04
JSON to Python with loads()
Use json.loads() when JSON data is already stored in a string.
Parse JSON
import json
text = '{"name": "Ali", "score": 92}'
data = json.loads(text)
print(data["name"])05
Reading and Writing JSON Files
For files, use json.dump() to write data and json.load() to read it back.
JSON file example
import json
data = {"course": "Python", "lessons": 73}
with open("course.json", "w", encoding="utf-8") as file:
json.dump(data, file, indent=2)
with open("course.json", "r", encoding="utf-8") as file:
loaded = json.load(file)
print(loaded["lessons"])06
Practice
Create a dictionary containing a student's name, age and subjects. Convert it to JSON, then load the JSON string back into Python and print the student's name.
You've reached the end of this lesson.
Continue in the Practice Lab and experiment with JSON data.