Bird
Raised Fist0
Pythonprogramming~20 mins

Serializing and deserializing JSON in Python - Practice Problems & Coding Challenges

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
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
What is the output of this JSON serialization code?
Consider this Python code that serializes a dictionary to a JSON string. What will be printed?
Python
import json

data = {'name': 'Alice', 'age': 30, 'is_student': False}
json_str = json.dumps(data)
print(json_str)
A{"name": "Alice", "age": 30, "is_student": True}
B{'name': 'Alice', 'age': 30, 'is_student': False}
C{"name": "Alice", "age": "30", "is_student": false}
D{"name": "Alice", "age": 30, "is_student": false}
Attempts:
2 left
💡 Hint
Remember that JSON uses double quotes and lowercase true/false for booleans.
Predict Output
intermediate
2:00remaining
What is the value of 'data' after deserializing this JSON string?
Given this JSON string, what Python object results from deserializing it?
Python
import json

json_str = '{"fruits": ["apple", "banana"], "count": 2}'
data = json.loads(json_str)
print(data)
A{'fruits': ['apple', 'banana'], 'count': 2}
B{"fruits": ["apple", "banana"], "count": 2}
C{fruits: ['apple', 'banana'], count: 2}
D['apple', 'banana', 2]
Attempts:
2 left
💡 Hint
json.loads converts JSON strings to Python dictionaries and lists.
Predict Output
advanced
2:00remaining
What error does this code raise when serializing?
What error will this code raise when trying to serialize the object to JSON?
Python
import json

class Person:
    def __init__(self, name):
        self.name = name

p = Person('Bob')
json_str = json.dumps(p)
ATypeError: Object of type Person is not JSON serializable
BValueError: Invalid JSON format
CAttributeError: 'Person' object has no attribute 'name'
DNo error, outputs '{}'
Attempts:
2 left
💡 Hint
json.dumps can only serialize basic Python types by default.
Predict Output
advanced
2:00remaining
What is the output of this code using json.loads with an invalid JSON string?
What happens when you run this code?
Python
import json

invalid_json = '{"name": "Alice", age: 30}'
data = json.loads(invalid_json)
A{'name': 'Alice', 'age': 30}
Bjson.decoder.JSONDecodeError: Expecting property name enclosed in double quotes
CSyntaxError: invalid syntax
DTypeError: string indices must be integers
Attempts:
2 left
💡 Hint
JSON keys must be double quoted strings.
🧠 Conceptual
expert
3:00remaining
Which option correctly serializes a Python dictionary with non-string keys to JSON?
Given a Python dictionary with integer keys, which option produces a valid JSON string with string keys?
Python
import json

data = {1: 'one', 2: 'two'}
Ajson.dumps(dict(map(str, data.items())))
Bjson.dumps(data)
Cjson.dumps({str(k): v for k, v in data.items()})
Djson.dumps(data, ensure_ascii=False)
Attempts:
2 left
💡 Hint
JSON keys must be strings. Python dict keys can be other types.

Practice

(1/5)
1. What does the json.dumps() function do in Python?
easy
A. Reads JSON data from a file
B. Converts Python data into a JSON formatted string
C. Converts JSON string back to Python data
D. Writes Python data directly to a file

Solution

  1. Step 1: Understand the purpose of json.dumps()

    This function takes Python objects like dictionaries or lists and turns them into a JSON string.
  2. Step 2: Differentiate from other JSON functions

    json.loads() converts JSON strings back to Python objects, while dumps() does the opposite.
  3. Final Answer:

    Converts Python data into a JSON formatted string -> Option B
  4. Quick Check:

    Serialize = Python to JSON string [OK]
Hint: Remember: dumps() means dump Python to JSON string [OK]
Common Mistakes:
  • Confusing dumps() with loads()
  • Thinking dumps() writes to a file
  • Assuming dumps() reads JSON data
2. Which of the following is the correct syntax to deserialize a JSON string json_str into a Python object?
easy
A. json.load(json_str)
B. json.dumps(json_str)
C. json.loads(json_str)
D. json.deserialize(json_str)

Solution

  1. Step 1: Identify the function to convert JSON string to Python

    The correct function is json.loads(), which takes a JSON string and returns Python data.
  2. Step 2: Check other options for correctness

    json.dumps() serializes Python to JSON string, json.load() reads JSON from a file object, and json.deserialize() does not exist.
  3. Final Answer:

    json.loads(json_str) -> Option C
  4. Quick Check:

    loads() = JSON string to Python [OK]
Hint: Use loads() to load JSON string into Python [OK]
Common Mistakes:
  • Using dumps() instead of loads()
  • Confusing load() with loads()
  • Using a non-existent deserialize() function
3. What will be the output of the following code?
import json
py_data = {'name': 'Alice', 'age': 30}
json_str = json.dumps(py_data)
print(type(json_str))
medium
A. <class 'dict'>
B. TypeError
C. <class 'list'>
D. <class 'str'>

Solution

  1. Step 1: Understand what json.dumps() returns

    The json.dumps() function converts Python data into a JSON string, so the result is a string type.
  2. Step 2: Check the printed type

    The type(json_str) will be <class 'str'> because json_str holds a JSON string.
  3. Final Answer:

    <class 'str'> -> Option D
  4. Quick Check:

    dumps() output type = str [OK]
Hint: dumps() returns a string, so type is str [OK]
Common Mistakes:
  • Thinking dumps() returns a dict
  • Confusing dumps() with loads()
  • Expecting a list type output
4. 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)
medium
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

  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]
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

  1. 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].
  2. Step 2: Serialize filtered list to JSON string

    Pass the filtered list to json.dumps() to get the JSON string.
  3. Final Answer:

    json.dumps([item for item in data if item['id'] > 1]) -> Option A
  4. Quick Check:

    Filter with list comprehension, then dumps() [OK]
Hint: Filter with list comprehension before dumps() [OK]
Common Mistakes:
  • Using filter() without converting to list
  • Trying to access dict keys with dot notation
  • Using filter() result directly without list()