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.
0
0
Serializing and deserializing JSON in Python
Introduction
Saving user settings to a file so they can be loaded later.
Sending data from a web app to a server.
Reading data from a file that was saved in JSON format.
Sharing data between different programs or devices.
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
This turns a Python dictionary into a JSON string.
Python
import json # Serialize a dictionary to JSON string data = {'name': 'Alice', 'age': 30} json_str = json.dumps(data) print(json_str)
This turns a JSON string back into a Python dictionary.
Python
import json # Deserialize JSON string back to dictionary json_str = '{"name": "Alice", "age": 30}' data = json.loads(json_str) print(data)
Lists can also be converted to JSON strings.
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)
OutputSuccess
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.