We use JSON to save or send data in a simple text format. Serializing turns data into JSON text. Deserializing turns JSON text back into data.
Serializing and deserializing JSON in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
import json # Serialize (convert data to JSON string) json_string = json.dumps(data) # Deserialize (convert JSON string back to data) data = json.loads(json_string)
json.dumps() converts Python data to a JSON string.
json.loads() converts a JSON string back to Python data.
Examples
Python
import json # Serialize a dictionary to JSON string data = {'name': 'Alice', 'age': 30} json_str = json.dumps(data) print(json_str)
Python
import json # Deserialize JSON string back to dictionary json_str = '{"name": "Alice", "age": 30}' data = json.loads(json_str) print(data)
Python
import json # Serialize a list to JSON string numbers = [1, 2, 3, 4] json_str = json.dumps(numbers) print(json_str)
Sample Program
This program shows how to convert a Python dictionary to a JSON string and back again.
Python
import json # Original data person = {'name': 'Bob', 'age': 25, 'city': 'New York'} # Serialize to JSON string json_data = json.dumps(person) print('Serialized JSON:', json_data) # Deserialize back to Python dictionary person_data = json.loads(json_data) print('Deserialized data:', person_data)
Important Notes
JSON only supports basic data types like strings, numbers, lists, and dictionaries.
Python objects like sets or custom classes need special handling before serializing.
Use indent parameter in json.dumps() to make JSON output easier to read.
Summary
Serializing means converting Python data to JSON text.
Deserializing means converting JSON text back to Python data.
Use the json module's dumps() and loads() functions for this.
Practice
1. What does the
json.dumps() function do in Python?easy
Solution
Step 1: Understand the purpose of
This function takes Python objects like dictionaries or lists and turns them into a JSON string.json.dumps()Step 2: Differentiate from other JSON functions
json.loads()converts JSON strings back to Python objects, whiledumps()does the opposite.Final Answer:
Converts Python data into a JSON formatted string -> Option BQuick 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
Solution
Step 1: Identify the function to convert JSON string to Python
The correct function isjson.loads(), which takes a JSON string and returns Python data.Step 2: Check other options for correctness
json.dumps()serializes Python to JSON string,json.load()reads JSON from a file object, andjson.deserialize()does not exist.Final Answer:
json.loads(json_str) -> Option CQuick 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
Solution
Step 1: Understand what json.dumps() returns
Thejson.dumps()function converts Python data into a JSON string, so the result is a string type.Step 2: Check the printed type
Thetype(json_str)will be<class 'str'>becausejson_strholds a JSON string.Final Answer:
<class 'str'> -> Option DQuick 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
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, usejson.loads()instead ofjson.load().Final Answer:
json.load() expects a file object, not a string -> Option AQuick 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
Solution
Step 1: Filter list with list comprehension
Use a list comprehension to select dictionaries whereidis greater than 1:[item for item in data if item['id'] > 1].Step 2: Serialize filtered list to JSON string
Pass the filtered list tojson.dumps()to get the JSON string.Final Answer:
json.dumps([item for item in data if item['id'] > 1]) -> Option AQuick 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()
