A. json.load() expects a file object, not a string
B. json_str is not a valid JSON string
C. json.loads() should be replaced with json.dumps()
D. Missing import statement for json module
Solution
Step 1: Understand the difference between json.load() and json.loads()
json.load() reads JSON data from a file-like object, not from a string.
Step 2: Identify correct function for string input
To convert a JSON string to Python data, use json.loads() instead of json.load().
Final Answer:
json.load() expects a file object, not a string -> Option A
Quick Check:
load() = file, loads() = string [OK]
Hint: Use loads() for strings, load() for files [OK]
Common Mistakes:
Using load() on a string instead of loads()
Assuming json_str is invalid JSON
Confusing dumps() and loads()
5. You have a Python list data = [{'id': 1}, {'id': 2}, {'id': 3}]. You want to serialize it to JSON but only include dictionaries where id is greater than 1. Which code correctly does this?
hard
A. json.dumps([item for item in data if item['id'] > 1])
B. json.dumps(data.filter(lambda x: x['id'] > 1))
C. json.dumps(filter(lambda x: x['id'] > 1, data))
D. json.dumps([item for item in data if item.id > 1])
Solution
Step 1: Filter list with list comprehension
Use a list comprehension to select dictionaries where id is greater than 1: [item for item in data if item['id'] > 1].
Step 2: Serialize filtered list to JSON string
Pass the filtered list to json.dumps() to get the JSON string.
Final Answer:
json.dumps([item for item in data if item['id'] > 1]) -> Option A
Quick Check:
Filter with list comprehension, then dumps() [OK]
Hint: Filter with list comprehension before dumps() [OK]