杰瑞科技汇

Python如何高效解析JSON数据?

Of course! Parsing JSON in Python is a common task, and the language has excellent built-in support for it. The primary module you'll use is the json module, which is part of Python's standard library, so no installation is needed.

Python如何高效解析JSON数据?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the basics, common use cases, and best practices.

The Basics: json.loads() and json.dumps()

The json module has two core functions:

  • json.loads(string): Parses a JSON string and converts it into a Python object (usually a dictionary or a list).
  • json.dumps(object): Takes a Python object (like a dictionary) and converts it into a JSON string.

The names are memorable if you think of them as:

  • loads: load string
  • dumps: dump string

Parsing JSON into Python Objects (json.loads)

Let's start with the most common task: taking a JSON string and turning it into something we can work with in Python.

Python如何高效解析JSON数据?-图2
(图片来源网络,侵删)

Example 1: Simple JSON Object

A JSON object becomes a Python dict.

import json
# A JSON string, typically from a file or an API response
json_string = '''
{
    "name": "John Doe",
    "age": 30,
    "isStudent": false,
    "courses": [
        {"title": "History", "credits": 3},
        {"title": "Math", "credits": 4}
    ]
}
'''
# Parse the JSON string into a Python dictionary
python_dict = json.loads(json_string)
# Now you can access the data like a normal Python dictionary
print(f"Name: {python_dict['name']}")
print(f"Age: {python_dict['age']}")
print(f"Is Student: {python_dict['isStudent']}")
# Access nested data
first_course_title = python_dict['courses'][0]['title']
print(f"First Course Title: {first_course_title}")

Output:

Name: John Doe
Age: 30
Is Student: False
First Course Title: History

JSON to Python Type Mapping

The json module automatically converts JSON types to their Python equivalents:

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

Reading JSON from a File (json.load)

When you have a JSON file (e.g., data.json), you should use json.load() (note: no 's'). It reads from a file object instead of a string.

Python如何高效解析JSON数据?-图3
(图片来源网络,侵删)

Step 1: Create a sample JSON file (data.json)

{
    "apiVersion": "v1",
    "data": {
        "DB_HOST": "localhost",
        "DB_PORT": "5432",
        "API_KEY": "xyz-abc-123"
    }
}

Step 2: Parse the file in Python

import json
# Use a 'with' statement for safe file handling
with open('data.json', 'r') as file:
    data = json.load(file) # Use json.load() (no 's') for file objects
print(data)
print(f"API Key: {data['data']['API_KEY']}")

Output:

{'apiVersion': 'v1', 'data': {'DB_HOST': 'localhost', 'DB_PORT': '5432', 'API_KEY': 'xyz-abc-123'}}
API Key: xyz-abc-123

Creating JSON from Python Objects (json.dumps)

Sometimes you need to send Python data to a web service or save it to a file in JSON format. This is where json.dumps() comes in.

import json
# A Python dictionary
python_data = {
    "name": "Jane Smith",
    "age": 28,
    "skills": ["Python", "SQL", "Docker"],
    "active": True
}
# Convert the Python dictionary to a JSON string
json_string = json.dumps(python_data)
print(json_string)

Output:

{"name": "Jane Smith", "age": 28, "skills": ["Python", "SQL", "Docker"], "active": true}

Making the JSON Pretty-Printed

The default output is compact. For debugging or human-readable files, use the indent parameter.

# Create a nicely formatted (pretty-printed) JSON string
pretty_json_string = json.dumps(python_data, indent=4)
print(pretty_json_string)

Output:

{
    "name": "Jane Smith",
    "age": 28,
    "skills": [
        "Python",
        "SQL",
        "Docker"
    ],
    "active": true
}

Other Useful dumps Parameters

  • sort_keys=True: Sorts the keys in the JSON output alphabetically.
  • ensure_ascii=False: Allows non-ASCII characters (like emojis or accented letters) to be included directly in the output, rather than being escaped.
data_with_unicode = {"name": "José", "city": "São Paulo"}
# With ensure_ascii=True (default)
json_ascii = json.dumps(data_with_unicode, indent=4)
print("--- ASCII Escaped ---")
print(json_ascii)
# With ensure_ascii=False
json_unicode = json.dumps(data_with_unicode, indent=4, ensure_ascii=False)
print("\n--- Unicode Direct ---")
print(json_unicode)

Writing to a JSON File (json.dump)

Similar to reading, to write a Python object to a JSON file, you use json.dump() (no 's'). It writes to a file object.

import json
python_data = {
    "username": "newuser",
    "email": "newuser@example.com",
    "preferences": {
        "theme": "dark",
        "notifications": True
    }
}
# Use a 'with' statement to open the file for writing
with open('user_profile.json', 'w') as file:
    # Use json.dump() (no 's') to write to the file object
    json.dump(python_data, file, indent=4)
print("File 'user_profile.json' created successfully.")

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

{
    "username": "newuser",
    "email": "newuser@example.com",
    "preferences": {
        "theme": "dark",
        "notifications": true
    }
}

Handling Errors

JSON parsing can fail if the string is not valid. Always wrap your parsing logic in a try...except block to handle potential json.JSONDecodeError exceptions.

import json
invalid_json_string = '{"name": "Bob", "age": "forty" }' # Missing a comma
try:
    python_dict = json.loads(invalid_json_string)
    print("Successfully parsed:", python_dict)
except json.JSONDecodeError as e:
    print(f"Error parsing JSON: {e}")
    print("Please check the format of your JSON string.")

Output:

Error parsing JSON: Expecting ',' delimiter: line 1 column 24 (char 23)
Please check the format of your JSON string.

Summary: Key Functions

Task Function Input Output
Parse a JSON string json.loads() JSON string Python object
Parse a JSON file json.load() File object Python object
Serialize a Python object to a string json.dumps() Python object JSON string
Serialize a Python object to a file json.dump() Python object Writes to a file
分享:
扫描分享到社交APP
上一篇
下一篇