Bird
Raised Fist0
Pythonprogramming~10 mins

Serializing and deserializing JSON 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 - Serializing and deserializing JSON
Start with Python object
Serialize: Convert to JSON string
JSON string ready for storage or transfer
Deserialize: Convert JSON string back to Python object
Python object restored
End
This flow shows how a Python object is turned into a JSON string (serialization) and then back into a Python object (deserialization).
Execution Sample
Python
import json

person = {"name": "Anna", "age": 28}
json_str = json.dumps(person)
print(json_str)
restored = json.loads(json_str)
print(restored)
This code converts a Python dictionary to a JSON string and then back to a dictionary, printing both.
Execution Table
StepActionInputOutputNotes
1Define Python dict{"name": "Anna", "age": 28}person dictCreate a Python dictionary named person
2Serialize with json.dumpsperson dict"{\"name\": \"Anna\", \"age\": 28}"Convert dict to JSON string
3Print JSON string"{\"name\": \"Anna\", \"age\": 28}"{"name": "Anna", "age": 28}Output JSON string to console
4Deserialize with json.loads"{\"name\": \"Anna\", \"age\": 28}"restored dictConvert JSON string back to dict
5Print restored dictrestored dict{'name': 'Anna', 'age': 28}Output restored dict to console
6EndProgram finishes
💡 All steps complete, JSON string successfully serialized and deserialized.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
personundefined{"name": "Anna", "age": 28}{"name": "Anna", "age": 28}{"name": "Anna", "age": 28}{"name": "Anna", "age": 28}
json_strundefinedundefined"{\"name\": \"Anna\", \"age\": 28}""{\"name\": \"Anna\", \"age\": 28}""{\"name\": \"Anna\", \"age\": 28}"
restoredundefinedundefinedundefined{"name": "Anna", "age": 28}{"name": "Anna", "age": 28}
Key Moments - 3 Insights
Why does json.dumps output a string with escaped quotes?
json.dumps converts the Python dict into a JSON string format, which uses double quotes around keys and strings. The backslashes escape these quotes inside the Python string representation. See execution_table step 2.
Is the restored object after json.loads exactly the same as the original Python dict?
Yes, json.loads converts the JSON string back into a Python dictionary with the same keys and values. See execution_table steps 4 and 5.
Can we use json.loads directly on a Python dict?
No, json.loads expects a JSON string, not a Python dict. You must serialize first with json.dumps. See execution_table step 2 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the type of json_str?
AA JSON formatted string
BA Python dictionary
CA list
DAn integer
💡 Hint
Check the Output column at step 2 in execution_table; it shows a string with escaped quotes.
At which step does the JSON string get converted back to a Python dictionary?
AStep 1
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the Action column in execution_table; json.loads is called at step 4.
If we skip json.dumps and try to print the dict directly, what changes in the output?
AOutput will be a JSON string
BOutput will be an error
COutput will be the Python dict representation
DOutput will be empty
💡 Hint
See variable_tracker for 'person' and json_str; json_str is the JSON string, person is the dict.
Concept Snapshot
Serializing: Use json.dumps(obj) to convert Python objects to JSON strings.
Deserializing: Use json.loads(json_str) to convert JSON strings back to Python objects.
JSON strings use double quotes and are text format.
Python dicts and JSON objects look similar but are different types.
Always serialize before sending/storing, deserialize when reading back.
Full Transcript
This lesson shows how to turn a Python dictionary into a JSON string using json.dumps, then back into a dictionary using json.loads. We start with a Python dict named person. Then json.dumps converts it to a JSON string with double quotes. This string can be stored or sent over a network. Later, json.loads reads the JSON string and recreates the original Python dictionary. We print both the JSON string and the restored dictionary to see the changes. Key points: json.dumps outputs a string with escaped quotes, json.loads requires a string input, and the restored object matches the original dictionary. This process is called serialization and deserialization.

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()