杰瑞科技汇

Python JSON对象如何创建与解析?

Of course! Let's break down how to work with JSON objects in Python, from basic reading and writing to more advanced topics.

Python JSON对象如何创建与解析?-图1
(图片来源网络,侵删)

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It's easy for humans to read and write, and easy for machines to parse and generate. It's the de-facto standard for data exchange on the web.

A JSON object looks very similar to a Python dictionary:

{
  "name": "John Doe",
  "age": 30,
  "isStudent": false,
  "courses": [
    "History",
    "Math",
    "Art"
  ],
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  }
}

The Core: json Module

Python's built-in json module is all you need to handle JSON data. It provides two main pairs of functions:

  1. json.dump() and json.dumps(): For encoding Python objects into JSON strings.
  2. json.load() and json.loads(): For decoding JSON strings into Python objects.

Let's break them down.

Python JSON对象如何创建与解析?-图2
(图片来源网络,侵删)

Loading JSON (Reading JSON into Python)

This is the process of taking a JSON string and converting it into a Python object (typically a dictionary or a list).

json.loads() (Load String)

Use this when your JSON data is already in a Python string.

import json
# A JSON string
json_string = '''
{
  "name": "John Doe",
  "age": 30,
  "isStudent": false,
  "courses": ["History", "Math", "Art"]
}
'''
# Convert the JSON string to a Python dictionary
python_dict = json.loads(json_string)
# Now you can work with it like a normal Python dictionary
print(python_dict)
print(f"Name: {python_dict['name']}")
print(f"First course: {python_dict['courses'][0]}")
print(f"Type of the loaded object: {type(python_dict)}")

Output:

{'name': 'John Doe', 'age': 30, 'isStudent': False, 'courses': ['History', 'Math', 'Art']}
Name: John Doe
First course: History
Type of the loaded object: <class 'dict'>

json.load() (Load from File)

Use this when your JSON data is stored in a .json file.

Let's say you have a file named data.json with the following content:

{
  "city": "New York",
  "population": 8400000
}

Here's how to read it:

import json
# Open the file in read mode ('r')
with open('data.json', 'r') as file:
    data_from_file = json.load(file)
# Work with the data
print(data_from_file)
print(f"City: {data_from_file['city']}")

Output:

{'city': 'New York', 'population': 8400000}
City: New York

Dumping JSON (Writing Python Objects to JSON)

This is the process of taking a Python object (like a dictionary) and converting it into a JSON string or writing it to a file.

json.dumps() (Dump String)

Use this to get a JSON string representation of a Python object. This is useful for sending data over an API or storing it in a database.

import json
# A Python dictionary
python_dict = {
  "name": "Jane Smith",
  "age": 28,
  "isStudent": True,
  "courses": ["Physics", "Chemistry"]
}
# Convert the Python dictionary to a JSON string
json_string = json.dumps(python_dict)
print(json_string)
print(f"Type of the dumped object: {type(json_string)}")

Output:

{"name": "Jane Smith", "age": 28, "isStudent": true, "courses": ["Physics", "Chemistry"]}
Type of the dumped object: <class 'str'>

You can make the JSON string more readable by using the indent parameter:

# Pretty-print the JSON string
pretty_json_string = json.dumps(python_dict, indent=4)
print(pretty_json_string)

Output:

{
    "name": "Jane Smith",
    "age": 28,
    "isStudent": true,
    "courses": [
        "Physics",
        "Chemistry"
    ]
}

json.dump() (Dump to File)

Use this to write a Python object directly to a .json file.

import json
# A Python dictionary
python_dict = {
  "product": "Laptop",
  "price": 1200.99,
  "in_stock": True
}
# Open the file in write mode ('w')
with open('product.json', 'w') as file:
    # Write the dictionary to the file as JSON
    # Use indent=4 for pretty-printing
    json.dump(python_dict, file, indent=4)
print("Data has been written to product.json")

After running this, a new file named product.json will be created with the following content:

{
    "product": "Laptop",
    "price": 1200.99,
    "in_stock": true
}

Common Pitfalls and Solutions

Pitfall 1: json.loads() on a non-string object

If you try to pass a file object or a non-string to json.loads(), you'll get a TypeError.

# WRONG
import json
with open('data.json', 'r') as f:
    # This will cause a TypeError
    data = json.loads(f) 

Solution: Use the correct function. For files, use json.load().

# CORRECT
import json
with open('data.json', 'r') as f:
    data = json.load(f)

Pitfall 2: TypeError: Object of type ... is not JSON serializable

The json module can only serialize basic Python types. If you try to dump a custom object (like a class instance), it will fail.

import json
import datetime
class User:
    def __init__(self, name, join_date):
        self.name = name
        self.join_date = join_date # This is a datetime object
user = User("Alice", datetime.datetime(2025, 1, 1))
# This will raise a TypeError
# json_string = json.dumps(user)

Solution: Provide a custom "encoder" that tells json how to handle your special object.

import json
import datetime
class User:
    def __init__(self, name, join_date):
        self.name = name
        self.join_date = join_date
class UserEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, User):
            # Return a dictionary representation of the User object
            return {
                'name': obj.name,
                'join_date': obj.join_date.isoformat() # Convert datetime to string
            }
        # Let the base class default method handle other types
        return super().default(obj)
user = User("Alice", datetime.datetime(2025, 1, 1))
# Now use the custom encoder
json_string = json.dumps(user, cls=UserEncoder, indent=4)
print(json_string)

Output:

{
    "name": "Alice",
    "join_date": "2025-01-01T00:00:00"
}

Summary Table

Function Action Input Output Common Use Case
json.loads() Load String JSON string Python dict/list Parsing JSON received from an API response.
json.load() Load from File File object Python dict/list Reading data from a local .json file.
json.dumps() Dump String Python dict/list JSON string Preparing data to send in an API request.
json.dump() Dump to File Python dict/list Writes to a file Saving Python data to a .json file for storage.
分享:
扫描分享到社交APP
上一篇
下一篇