Working with JSON Files
Working with JSON Files
Many modern apps store data in JSON files.
JSON is used for:
- Settings
- User data
- APIs
- Web apps
- Config files
Python can read and write JSON easily.
What Is JSON?
JSON means JavaScript Object Notation.
It stores structured data using keys and values.
Example file: user.json
{
"name": "Tom",
"age": 25,
"city": "New York"
}
It looks similar to a Python dictionary.
Why JSON Matters
JSON is useful because it:
- Stores structured data
- Is easy to read
- Is used by many apps
- Works well with APIs
Import the json Module
Python has a built-in module called json.
import json
Reading JSON from a File
Use json.load().
import json
with open("user.json") as file:
data = json.load(file)
print(data)
print(data["name"])
Output
{'name': 'Tom', 'age': 25, 'city': 'New York'}
Tom
Writing JSON to a File
Use json.dump().
import json
user = {
"name": "Sara",
"age": 30
}
with open("user.json", "w") as file:
json.dump(user, file)
File Content
{"name": "Sara", "age": 30}
Pretty JSON Output
Use indent=4.
import json
user = {
"name": "Sara",
"age": 30
}
with open("user.json", "w") as file:
json.dump(user, file, indent=4)
File Content
{
"name": "Sara",
"age": 30
}
List of Dictionaries in JSON
JSON can store lists too.
import json
students = [
{"name": "Tom", "score": 85},
{"name": "Sara", "score": 92}
]
with open("students.json", "w") as file:
json.dump(students, file, indent=4)
Reading the List Back
import json
with open("students.json") as file:
students = json.load(file)
for student in students:
print(student["name"], student["score"])
Output
Tom 85
Sara 92
Common Beginner Errors
Forgetting import json
The code will not work.
Wrong File Name
Check spelling carefully.
Invalid JSON Format
Missing commas or quotes can cause errors.
Code Along
Create a dictionary with:
{
"theme": "dark",
"language": "English"
}
Save it into settings.json.
Mini Challenge
Build a profile saver.
Steps:
- Create this dictionary:
{
"name": "Tom",
"age": 25,
"skills": ["Python", "HTML"]
}
- Save it into
profile.json - Read the file
- Print name
- Print all skills
Expected output:
Tom
Python
HTML
Real World Use Case
Programs use JSON for settings, saved data, APIs, game data, and user profiles.
Quiz
- What does JSON stand for?
- Which function reads JSON from a file?
- Which function writes JSON to a file?
- Why use
indent=4?
Assignment
Create a book.json file with title, price, and author. Read it and print the values.
Summary
You learned how to read JSON files, write JSON files, store lists in JSON, and use structured data in Python.