Bird
Raised Fist0

The following code raises an error. What is the mistake?

medium📝 Debug Q14 of Q15
Python - Structured Data Files
The following code raises an error. What is the mistake?
import json
json_str = '{"name": "Bob", "age": 25}'
py_data = json.load(json_str)
print(py_data)
Ajson.load() expects a file object, not a string
Bjson_str is not a valid JSON string
Cjson.loads() should be replaced with json.dumps()
DMissing import statement for json module
Step-by-Step Solution
Solution:
  1. 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.
  2. Step 2: Identify correct function for string input

    To convert a JSON string to Python data, use json.loads() instead of json.load().
  3. Final Answer:

    json.load() expects a file object, not a string -> Option A
  4. Quick Check:

    load() = file, loads() = string [OK]
Quick Trick: Use loads() for strings, load() for files [OK]
Common Mistakes:
MISTAKES
  • Using load() on a string instead of loads()
  • Assuming json_str is invalid JSON
  • Confusing dumps() and loads()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes