Andromeda
Note

JSON Data Serialization (Python)

Definition

The process of converting Python data structures (lists, dictionaries, etc.) into a JSON (JavaScript Object Notation) formatted string for storage or transmission, and converting them back into Python objects.

Why It Matters

In a connected world, “what” you know matters less than how you share it. JSON serialization is the universal translator that allows different programs and languages to exchange complex data structures seamlessly, powering the modern API-driven internet.

Core Concepts

  • Serialization Methods:
    • json.loads(string): Parses a JSON-formatted string into a Python dictionary/list.
    • json.dumps(obj): Converts a Python object into a JSON-formatted string.
    • The “S” Rule: The ‘s’ in loads and dumps stands for string. Use load() and dump() (no ‘s’) for reading/writing directly to file objects.
  • Example Usage:
import json

data = {"user": "alice", "active": True, "roles": ["admin", "dev"]}

# Serialize to string
json_string = json.dumps(data, indent=4)

# Deserialize back to dictionary
parsed_data = json.loads(json_string)
print(f"User {parsed_data['user']} is active: {parsed_data['active']}")
  • Data Type Constraints: JSON can only store: Strings, Numbers, Booleans, Lists, Dictionaries, and None. It cannot natively store Python-specific types like Tuples, Datetime objects, or custom Classes.
  • Interoperability: JSON is a language-independent format, making it the “lingua franca” of the modern web for sharing data between different systems.

Connected Concepts