Bird
Raised Fist0
Pythonprogramming~10 mins

Working with JSON files in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Working with JSON files
Open JSON file in read mode
Read file content as string
Parse string to Python object (dict/list)
Use or modify Python object
Open JSON file in write mode
Convert Python object to JSON string
Write JSON string to file
Close file
This flow shows how Python reads JSON data from a file into Python objects, modifies them, then writes back as JSON.
Execution Sample
Python
import json

with open('data.json', 'r') as f:
    data = json.load(f)

print(data['name'])
This code reads JSON from 'data.json' file and prints the value of the 'name' key.
Execution Table
StepActionCode LineResult/Value
1Open 'data.json' file in read modewith open('data.json', 'r') as f:File object 'f' opened
2Read JSON content and parse to Python dictdata = json.load(f){'name': 'Alice', 'age': 30}
3Access 'name' key in dictprint(data['name'])Alice
4File 'data.json' automatically closedEnd of with blockFile closed
💡 File is closed after reading; program prints 'Alice' and ends.
Variable Tracker
VariableStartAfter json.loadFinal
fNoneFile object openedFile closed
dataNone{'name': 'Alice', 'age': 30}{'name': 'Alice', 'age': 30}
Key Moments - 3 Insights
Why do we use 'with open(...) as f' instead of just open()?
Using 'with' ensures the file is properly closed after reading, even if errors occur, as shown in step 4 of the execution_table.
What type is 'data' after json.load(f)?
'data' becomes a Python dictionary representing the JSON object, as seen in step 2 where data = {'name': 'Alice', 'age': 30}.
What happens if the JSON file is empty or malformed?
json.load(f) will raise an error and stop execution; this is why proper JSON format is required before loading.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'data' after step 2?
ANone
BFile object
C{'name': 'Alice', 'age': 30}
D'Alice'
💡 Hint
Check the 'Result/Value' column in row with Step 2 in execution_table.
At which step is the file closed?
AStep 4
BStep 2
CStep 1
DStep 3
💡 Hint
Look at the 'Action' column in execution_table for file closing.
If the JSON file contained a list instead of a dict, what would 'data' be after json.load(f)?
AA string
BA Python list
CA file object
DAn integer
💡 Hint
json.load converts JSON arrays to Python lists, similar to how it converts JSON objects to dicts.
Concept Snapshot
Working with JSON files in Python:
- Use 'import json' module
- Open file with 'with open(filename, mode) as f'
- Read JSON with 'json.load(f)' to get Python dict/list
- Modify Python object as needed
- Write back with 'json.dump(obj, f)'
- 'with' block auto-closes file
- JSON maps to Python types (object->dict, array->list)
Full Transcript
This lesson shows how Python reads and writes JSON files. First, the program opens a JSON file in read mode using a 'with' statement, which safely manages the file. Then it reads the file content and parses it into a Python dictionary using json.load. The program accesses data from this dictionary, for example printing the value of the 'name' key. After the 'with' block ends, the file is automatically closed. This process allows Python programs to work with JSON data easily by converting it to familiar Python objects. Writing JSON back to a file uses a similar process with json.dump. Understanding these steps helps beginners handle JSON files safely and effectively.

Practice

(1/5)
1.

What is the main purpose of using JSON files in Python programs?

easy
A. To create graphical user interfaces
B. To execute Python code faster
C. To save and load data in a simple text format
D. To compile Python programs into executables

Solution

  1. Step 1: Understand JSON file usage

    JSON files store data in a text format that is easy to read and share.
  2. Step 2: Identify the correct purpose

    Saving and loading data simply matches the main use of JSON files in Python.
  3. Final Answer:

    To save and load data in a simple text format -> Option C
  4. Quick Check:

    JSON files = data storage [OK]
Hint: JSON files store data simply as text [OK]
Common Mistakes:
  • Thinking JSON speeds up code execution
  • Confusing JSON with GUI creation
  • Assuming JSON compiles code
2.

Which of the following is the correct way to open a JSON file named data.json for reading in Python?

easy
A. open('data.json', 'r')
B. open('data.json', 'w')
C. open('data.json', 'a')
D. open('data.json', 'x')

Solution

  1. Step 1: Understand file modes

    'r' mode opens a file for reading, 'w' for writing, 'a' for appending, 'x' for creating new file.
  2. Step 2: Choose mode for reading JSON

    To read JSON data, the file must be opened in 'r' mode.
  3. Final Answer:

    open('data.json', 'r') -> Option A
  4. Quick Check:

    Read mode = 'r' [OK]
Hint: Use 'r' mode to read files [OK]
Common Mistakes:
  • Using 'w' which overwrites the file
  • Using 'a' which appends data
  • Using 'x' which fails if file exists
3.

What will be the output of the following Python code?

import json

with open('data.json', 'w') as f:
    json.dump({'name': 'Alice', 'age': 30}, f)

with open('data.json', 'r') as f:
    data = json.load(f)
print(data['age'])

medium
A. Alice
B. 30
C. {'name': 'Alice', 'age': 30}
D. Error: file not found

Solution

  1. Step 1: Write dictionary to JSON file

    The code writes {'name': 'Alice', 'age': 30} to 'data.json' using json.dump.
  2. Step 2: Read JSON file and access 'age'

    json.load reads the file back as a dictionary, then data['age'] accesses the value 30.
  3. Final Answer:

    30 -> Option B
  4. Quick Check:

    data['age'] = 30 [OK]
Hint: json.load returns Python dict from JSON file [OK]
Common Mistakes:
  • Expecting string output instead of integer
  • Confusing json.dump and json.load usage
  • Assuming file read fails without writing first
4.

Identify the error in this code snippet that tries to read JSON data from a file:

import json

f = open('data.json', 'r')
data = json.load(f)
f.close()
print(data)

medium
A. Missing import statement for json
B. File not opened in write mode
C. File not closed properly
D. No error, code works correctly

Solution

  1. Step 1: Check import and file open

    The code imports json and opens the file in 'r' mode correctly.
  2. Step 2: Verify json.load and file close

    json.load reads JSON data properly, and file is closed with f.close().
  3. Final Answer:

    No error, code works correctly -> Option D
  4. Quick Check:

    Code reads JSON file correctly [OK]
Hint: json.load needs file opened in 'r' mode [OK]
Common Mistakes:
  • Forgetting to import json
  • Opening file in wrong mode
  • Not closing the file after reading
5.

You want to save a Python dictionary {'a': 1, 'b': 2, 'c': 3} to a JSON file and then read it back. Which code snippet correctly does this and prints the value of key 'b'?

hard
A.
import json
with open('file.json', 'w') as f:
    json.dump({'a': 1, 'b': 2, 'c': 3}, f)
with open('file.json', 'r') as f:
    data = json.load(f)
print(data['b'])
B.
import json
with open('file.json', 'r') as f:
    json.dump({'a': 1, 'b': 2, 'c': 3}, f)
with open('file.json', 'w') as f:
    data = json.load(f)
print(data['b'])
C.
import json
f = open('file.json', 'w')
json.load({'a': 1, 'b': 2, 'c': 3}, f)
f.close()
f = open('file.json', 'r')
data = json.dump(f)
f.close()
print(data['b'])
D.
import json
with open('file.json', 'w') as f:
    json.load({'a': 1, 'b': 2, 'c': 3}, f)
with open('file.json', 'r') as f:
    data = json.dump(f)
print(data['b'])

Solution

  1. Step 1: Write dictionary to JSON file correctly

    json.dump writes Python dict to file opened in 'w' mode.
    import json
    with open('file.json', 'w') as f:
        json.dump({'a': 1, 'b': 2, 'c': 3}, f)
    with open('file.json', 'r') as f:
        data = json.load(f)
    print(data['b'])
    does this correctly.
  2. Step 2: Read JSON file and access key 'b'

    json.load reads JSON back from file opened in 'r' mode, then data['b'] prints 2.
  3. Final Answer:

    Code in Option A correctly saves and reads JSON, printing 2 -> Option A
  4. Quick Check:

    json.dump to write, json.load to read [OK]
Hint: Use json.dump to write, json.load to read JSON files [OK]
Common Mistakes:
  • Using json.load to write data
  • Using json.dump to read data
  • Opening files in wrong modes