0
0
Pythonprogramming~20 mins

Working with JSON files in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
JSON Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Reading JSON data from a file
What is the output of this Python code that reads a JSON file and prints the data?
Python
import json
with open('data.json', 'r') as file:
    data = json.load(file)
print(data)
A{'name': 'Alice', 'age': 30}
B"{'name': 'Alice', 'age': 30}"
CSyntaxError
DFileNotFoundError
Attempts:
2 left
💡 Hint
Remember json.load reads JSON and converts it to Python objects.
Predict Output
intermediate
2:00remaining
Writing Python dictionary to JSON file
What will be the content of 'output.json' after running this code?
Python
import json
data = {'city': 'Paris', 'population': 2148327}
with open('output.json', 'w') as f:
    json.dump(data, f)
A{"city": "Paris", "population": 2148327}
B{'city': 'Paris', 'population': 2148327}
CSyntaxError
DTypeError
Attempts:
2 left
💡 Hint
json.dump writes JSON formatted string to file with double quotes.
Predict Output
advanced
2:00remaining
Handling JSON decoding errors
What error will this code raise when trying to load invalid JSON content?
Python
import json
invalid_json = '{"name": "Bob", age: 25}'
data = json.loads(invalid_json)
ATypeError
BNo error, data is loaded
CKeyError
Djson.decoder.JSONDecodeError
Attempts:
2 left
💡 Hint
JSON keys must be in double quotes.
Predict Output
advanced
2:00remaining
Using json.dumps with indentation
What is the output of this code?
Python
import json
data = {'fruit': 'apple', 'count': 5}
result = json.dumps(data, indent=2)
print(result)
A{"fruit": "apple", "count": 5}
B
{
  "fruit": "apple",
  "count": 5
}
CSyntaxError
DTypeError
Attempts:
2 left
💡 Hint
indent=2 adds line breaks and spaces for readability.
🧠 Conceptual
expert
2:00remaining
Understanding JSON serialization of custom objects
What happens when you run this code?
Python
import json
class Person:
    def __init__(self, name):
        self.name = name
p = Person('Eve')
json.dumps(p)
A{"name": "Eve"}
B"{'name': 'Eve'}"
CTypeError: Object of type Person is not JSON serializable
DNo output, code runs silently
Attempts:
2 left
💡 Hint
json.dumps can only serialize basic Python types by default.