杰瑞科技汇

Python JSON 类如何序列化与反序列化?

Of course! The phrase "Python JSON class" can mean a few different things. I'll cover the most common interpretations, from the built-in library to creating your own classes that work with JSON.

The json Module (The Standard Library)

This is the most fundamental way to handle JSON in Python. It's not a single class, but a module with functions to serialize (convert Python to JSON) and deserialize (convert JSON to Python).

The key functions are:

  • json.dumps(): Dump String - Converts a Python object to a JSON formatted string.
  • json.loads(): Load String - Converts a JSON formatted string into a Python object.
  • json.dump(): Dump - Writes a Python object to a file-like object.
  • json.load(): Load - Reads a JSON file-like object and converts it to a Python object.

Basic Usage Example

import json
# --- Python to JSON (Serialization) ---
# A Python dictionary
python_data = {
    "name": "John Doe",
    "age": 30,
    "isStudent": False,
    "courses": ["History", "Math"],
    "address": {
        "street": "123 Main St",
        "city": "Anytown"
    }
}
# Convert the Python dictionary to a JSON string
json_string = json.dumps(python_data)
print("Python Object:")
print(python_data)
print("\nJSON String:")
print(json_string)
print(f"Type: {type(json_string)}")
# You can make the JSON string more readable with indent
pretty_json_string = json.dumps(python_data, indent=4)
print("\nPretty JSON String:")
print(pretty_json_string)
# --- JSON to Python (Deserialization) ---
# A JSON string
json_string_to_parse = '{"name": "Jane Doe", "age": 25, "isStudent": true, "courses": ["Physics", "Chemistry"]}'
# Convert the JSON string to a Python dictionary
python_object = json.loads(json_string_to_parse)
print("\nParsed Python Object:")
print(python_object)
print(f"Type: {type(python_object)}")
# You can now access the data like a normal dictionary
print(f"Name: {python_object['name']}")
print(f"First course: {python_object['courses'][0]}")

Mapping Between Python and JSON

JSON Type Python Type
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

Creating a Class that Handles JSON

Often, you'll want to work with JSON data by representing it as a class instance. This provides structure, type hinting, and methods. The standard way to do this is using dataclasses.

Method A: Using dataclasses (Modern & Recommended)

This is the cleanest and most Pythonic way to create a class from JSON data.

Step 1: Define the dataclass

from dataclasses import dataclass
from typing import List, Dict
@dataclass
class Address:
    street: str
    city: str
@dataclass
class Person:
    name: str
    age: int
    is_student: bool
    courses: List[str]
    address: Address

Step 2: Create instances from JSON

You need a helper function to convert the JSON dictionary into your class instances.

import json
# The same JSON string as before
json_string = """
{
    "name": "John Doe",
    "age": 30,
    "isStudent": true,
    "courses": ["History", "Math"],
    "address": {
        "street": "123 Main St",
        "city": "Anytown"
    }
}
"""
def from_dict(data_class, data_dict):
    """Recursively converts a dictionary to a dataclass instance."""
    if isinstance(data_dict, dict):
        # Create an instance of the dataclass
        field_types = data_class.__annotations__
        kwargs = {}
        for field_name, field_type in field_types.items():
            if field_name in data_dict:
                # Recursively handle nested dataclasses
                if hasattr(field_type, "__dataclass_fields__"):
                    kwargs[field_name] = from_dict(field_type, data_dict[field_name])
                else:
                    kwargs[field_name] = data_dict[field_name]
        return data_class(**kwargs)
    # If it's not a dict, return it as is (e.g., for a list)
    return data_dict
# Convert JSON string to a Python dictionary
data_dict = json.loads(json_string)
# Convert the dictionary to a Person instance
person_instance = from_dict(Person, data_dict)
# Now you have a structured object!
print(person_instance)
# Output: Person(name='John Doe', age=30, is_student=True, courses=['History', 'Math'], address=Address(street='123 Main St', city='Anytown'))
print(f"Name: {person_instance.name}")
print(f"City: {person_instance.address.city}")
print(f"Is Student: {person_instance.is_student}")

Method B: Using __init__ and to_dict (Manual Approach)

You can also do this manually without the dataclass decorator. This gives you more control over the logic.

class AddressManual:
    def __init__(self, street: str, city: str):
        self.street = street
        self.city = city
    def to_dict(self):
        return {"street": self.street, "city": self.city}
class PersonManual:
    def __init__(self, name: str, age: int, is_student: bool, courses: list, address: AddressManual):
        self.name = name
        self.age = age
        self.is_student = is_student
        self.courses = courses
        self.address = address
    def to_dict(self):
        return {
            "name": self.name,
            "age": self.age,
            "isStudent": self.is_student,
            "courses": self.courses,
            "address": self.address.to_dict()
        }
# --- Usage ---
# Create an instance from a dictionary (like from JSON)
data = {
    "name": "Jane Doe",
    "age": 25,
    "isStudent": False,
    "courses": ["Art"],
    "address": {"street": "456 Oak Ave", "city": "Otherville"}
}
address = AddressManual(**data["address"])
person = PersonManual(**data)
print("--- Manual Class Example ---")
print(person.name)
# Convert the instance back to a dictionary (for JSON serialization)
person_dict = person.to_dict()
print(person_dict)

Third-Party Libraries (Powerful Alternatives)

For more complex scenarios, these libraries are fantastic.

Pydantic

Pydantic is extremely popular for data validation and settings management. It's a dataclass on steroids. It automatically validates data when you create an instance and can easily parse JSON.

Installation: pip install pydantic

from pydantic import BaseModel
from typing import List
class AddressPydantic(BaseModel):
    street: str
    city: str
class PersonPydantic(BaseModel):
    name: str
    age: int
    is_student: bool
    courses: List[str]
    address: AddressPydantic
# Pydantic can parse JSON directly into an instance!
json_string = """
{
    "name": "Peter Jones",
    "age": 42,
    "is_student": false,
    "courses": ["Economics"],
    "address": {
        "street": "789 Pine Ln",
        "city": "Big City"
    }
}
"""
# This one line does the parsing AND validation
person_pydantic = PersonPydantic.model_validate_json(json_string)
print("--- Pydantic Example ---")
print(person_pydantic)
print(f"Type of name: {type(person_pydantic.name)}")
print(f"Type of address: {type(person_pydantic.address)}")
# It also serializes back to JSON easily
print("\nBack to JSON:")
print(person_pydantic.model_dump_json(indent=2))

orjson

orjson is a fast, correct JSON library for Python. It's a drop-in replacement for the standard json library but is significantly faster, especially for large data. It's great for performance-critical applications.

Installation: pip install orjson

import orjson
python_data = {"name": "Fast User", "id": 12345}
# Serialize
json_bytes = orjson.dumps(python_data)
print(f"orjson output type: {type(json_bytes)}") # Note: it returns bytes
# Deserialize
python_object_back = orjson.loads(json_bytes)
print(python_object_back)

Summary: Which One to Use?

Scenario Recommended Tool Why
Simple serialization/deserialization json module It's built-in, standard, and perfect for basic tasks.
Representing JSON data as structured objects dataclasses Clean, readable, and Pythonic. The standard for modern Python.
Need robust data validation Pydantic The gold standard. Validates data on creation, great for APIs and configs.
Maximum performance orjson Blazing fast, a must-have for processing large JSON payloads.
分享:
扫描分享到社交APP
上一篇
下一篇