杰瑞科技汇

Python JSON如何转为字典?

Of course! Converting a JSON string to a Python dictionary is a very common task. The standard library has a built-in module called json that makes this process straightforward.

Python JSON如何转为字典?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the basics to more advanced scenarios.

The Short and Sweet Answer

Use the json.loads() function. "loads" stands for load string.

import json
# 1. Your JSON data as a string (note the single quotes for the Python string)
json_string = '{"name": "John Doe", "age": 30, "isStudent": false, "courses": ["History", "Math"]}'
# 2. Convert the JSON string to a Python dictionary
python_dict = json.loads(json_string)
# 3. Now you can work with it like a normal dictionary
print(python_dict)
# Output: {'name': 'John Doe', 'age': 30, 'isStudent': False, 'courses': ['History', 'Math']}
print(python_dict['name'])
# Output: John Doe
print(python_dict['courses'][0])
# Output: History

Key Concepts: JSON vs. Python

The json module automatically handles the conversion between JSON types and Python types. Here's a quick reference:

JSON Type Python Type Example
object dict {"key": "value"}
array list ["item1", "item2"]
string str "a string"
number (int) int 123
number (float) float 14
true True true
false False false
null None null

Common Pitfalls and How to Avoid Them

json.decoder.JSONDecodeError: Expecting value

This is the most common error. It happens when you try to parse a string that is not valid JSON.

Python JSON如何转为字典?-图2
(图片来源网络,侵删)

Cause 1: Using single quotes for keys or strings

JSON requires double quotes () around strings and keys. Python allows single quotes (), but json.loads() does not.

# This will FAIL!
invalid_json_string = "{'name': 'John', 'city': 'New York'}"
try:
    json.loads(invalid_json_string)
except json.JSONDecodeError as e:
    print(f"Error: {e}")
    # Output: Error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Solution: Make sure your JSON string uses double quotes.

# This will SUCCEED
valid_json_string = '{"name": "John", "city": "New York"}'
python_dict = json.loads(valid_json_string)
print(python_dict)
# Output: {'name': 'John', 'city': 'New York'}

Cause 2: Trailing Commas

Python JSON如何转为字典?-图3
(图片来源网络,侵删)

JSON does not allow a trailing comma after the last item in an object or array.

# This will FAIL!
invalid_json_string = '{"name": "John", "age": 30,}' # Note the comma after 30
try:
    json.loads(invalid_json_string)
except json.JSONDecodeError as e:
    print(f"Error: {e}")
    # Output: Error: Expecting property name enclosed in double quotes: line 1 column 20 (char 19)

Solution: Remove the trailing comma.

# This will SUCCEED
valid_json_string = '{"name": "John", "age": 30}'
python_dict = json.loads(valid_json_string)
print(python_dict)
# Output: {'name': 'John', 'age': 30}

Loading from a File

Often, your JSON data will be in a file (e.g., data.json). For this, you use json.load() (note: no 's'). This function reads from a file object.

File: data.json

{
  "id": 1,
  "product": "Laptop",
  "price": 1200.50,
  "in_stock": true
}

Python Script:

import json
# Open the file in read mode ('r')
with open('data.json', 'r') as file:
    # Use json.load() to convert the file's content to a dictionary
    data_dict = json.load(file)
# Now you can use the dictionary
print(data_dict)
# Output: {'id': 1, 'product': 'Laptop', 'price': 1200.5, 'in_stock': True}
print(f"The product is {data_dict['product']}.")
# Output: The product is Laptop.

Handling Special Characters (Non-ASCII)

If your JSON contains characters like , , or , you need to tell json.loads() how to decode them.

Scenario: Your JSON string is encoded in UTF-8 but is represented as a Python byte string (bytes).

# A byte string encoded in UTF-8
json_bytes_string = b'{"city": "M\xfcnchen"}' # \xfc is the UTF-8 for 'ü'
# By default, this will fail or produce 'M\xfcnchen'
# try:
#     print(json.loads(json_bytes_string))
# except TypeError as e:
#     print(f"Error: {e}") # Error: the JSON object must be str, bytes or bytearray, not 'str'
# Solution: Use the `encoding` argument
decoded_dict = json.loads(json_bytes_string, encoding='utf-8')
print(decoded_dict)
# Output: {'city': 'München'}

Advanced: Custom Decoding with object_hook

Sometimes you need to convert JSON objects into custom Python classes instead of plain dictionaries. You can do this with the object_hook parameter.

Let's say you want to convert all JSON "user" objects into a User class.

import json
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
    def __repr__(self):
        return f"User(name='{self.name}', email='{self.email}')"
# A JSON string with nested objects
json_string = '''
{
  "id": 123,
  "user": {
    "name": "Jane Doe",
    "email": "jane.doe@example.com"
  },
  "status": "active"
}
'''
def user_decoder(obj):
    """This function is called for every JSON object."""
    if 'name' in obj and 'email' in obj:
        # If the object has 'name' and 'email', it's a user
        return User(obj['name'], obj['email'])
    # Otherwise, return the object as a normal dict
    return obj
# Use object_hook to apply our custom decoder
data = json.loads(json_string, object_hook=user_decoder)
print(data)
# Output:
# {
#   'id': 123,
#   'user': User(name='Jane Doe', email='jane.doe@example.com'),
#   'status': 'active'
# }
print(data['user'])
# Output: User(name='Jane Doe', email='jane.doe@example.com')
print(type(data['user']))
# Output: <class '__main__.User'>
print(type(data)) # The top-level object is still a dict
# Output: <class 'dict'>

Summary

Task Function to Use
Parse a JSON string into a dictionary json.loads()
Parse a JSON file into a dictionary json.load()
Convert a Python dictionary to a JSON string json.dumps()
Write a Python dictionary to a JSON file json.dump()
分享:
扫描分享到社交APP
上一篇
下一篇