CodingNic

Files, Errors, and Automation

Working with JSON Files

Files, Errors, and Automation 28 min read

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

text
{
    "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.

python
import json

Reading JSON from a File

Use json.load().

python
import json

with open("user.json") as file:
    data = json.load(file)

print(data)
print(data["name"])

Output

text
{'name': 'Tom', 'age': 25, 'city': 'New York'}
Tom

Writing JSON to a File

Use json.dump().

python
import json

user = {
    "name": "Sara",
    "age": 30
}

with open("user.json", "w") as file:
    json.dump(user, file)

File Content

text
{"name": "Sara", "age": 30}

Pretty JSON Output

Use indent=4.

python
import json

user = {
    "name": "Sara",
    "age": 30
}

with open("user.json", "w") as file:
    json.dump(user, file, indent=4)

File Content

text
{
    "name": "Sara",
    "age": 30
}

List of Dictionaries in JSON

JSON can store lists too.

python
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

python
import json

with open("students.json") as file:
    students = json.load(file)

for student in students:
    print(student["name"], student["score"])

Output

text
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:

python
{
    "theme": "dark",
    "language": "English"
}

Save it into settings.json.

Mini Challenge

Build a profile saver.

Steps:

  • Create this dictionary:
python
{
    "name": "Tom",
    "age": 25,
    "skills": ["Python", "HTML"]
}
  • Save it into profile.json
  • Read the file
  • Print name
  • Print all skills

Expected output:

text
Tom
Python
HTML

Real World Use Case

Programs use JSON for settings, saved data, APIs, game data, and user profiles.

Quiz

  1. What does JSON stand for?
  2. Which function reads JSON from a file?
  3. Which function writes JSON to a file?
  4. 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.