JSON(JavaScript Object Notation)是一種輕量級的數(shù)據(jù)交換格式,易于人閱讀和編寫,也易于機(jī)器解析和生成。在Python中處理JSON數(shù)據(jù)是一個(gè)常見任務(wù),尤其是在與Web API交互時(shí)。Python提供了內(nèi)置的json模塊來處理JSON數(shù)據(jù)。小編將介紹如何使用Python處理JSON數(shù)據(jù),包括讀取、解析、生成和寫入JSON數(shù)據(jù)的基本操作。
1. Python的json模塊
Python的json模塊提供了處理JSON數(shù)據(jù)的基本方法,包括將Python對象編碼為JSON格式以及將JSON格式的數(shù)據(jù)解碼為Python對象。
導(dǎo)入json模塊
import json
2. 將Python對象編碼為JSON格式
Python提供了json.dumps()方法將Python對象轉(zhuǎn)換為JSON格式的字符串。
import json
# Python對象
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Wonderland"
}
}
# 將Python對象轉(zhuǎn)換為JSON字符串
json_str = json.dumps(data, indent=4)
print(json_str)
json.dumps():將Python對象轉(zhuǎn)換為JSON字符串。
indent參數(shù):用于美化JSON字符串的格式,指定縮進(jìn)的空格數(shù)。
處理JSON編碼時(shí)的注意事項(xiàng)
Python的None會(huì)被轉(zhuǎn)換為null。
Python的True和False會(huì)被轉(zhuǎn)換為true和false。
不支持的數(shù)據(jù)類型(如自定義對象)需要先轉(zhuǎn)換為可序列化的類型。
# 自定義對象的處理
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 25)
# 使用自定義的序列化函數(shù)
def person_encoder(obj):
if isinstance(obj, Person):
return {"name": obj.name, "age": obj.age}
raise TypeError(f"Type {obj.__class__.__name__} not serializable")
json_str = json.dumps(person, default=person_encoder, indent=4)
print(json_str)
3. 從JSON字符串解碼為Python對象
使用json.loads()方法將JSON格式的字符串解析為Python對象。
import json
# JSON字符串
json_str = '''
{
"name": "Alice",
"age": 30,
"is_student": false,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Wonderland"
}
}
'''
# 將JSON字符串解析為Python對象
data = json.loads(json_str)
print(data)
處理JSON解碼時(shí)的注意事項(xiàng)
JSON字符串中的null會(huì)被轉(zhuǎn)換為Python的None。
JSON字符串中的true和false會(huì)被轉(zhuǎn)換為Python的True和False。
如果JSON數(shù)據(jù)格式不正確,json.loads()會(huì)引發(fā)JSONDecodeError異常。
import json
invalid_json_str = '{"name": "Alice", "age": 30,}'
try:
data = json.loads(invalid_json_str)
except json.JSONDecodeError as e:
print(f"JSONDecodeError: {e}")
4. 從文件讀取和寫入JSON數(shù)據(jù)
json模塊還提供了用于從文件讀取和寫入JSON數(shù)據(jù)的方法,即json.load()和json.dump()。
將Python對象寫入JSON文件
import json
data = {
"name": "Bob",
"age": 25,
"is_student": True,
"courses": ["History", "Literature"],
"address": {
"street": "456 Elm St",
"city": "Metropolis"
}
}
with open('data.json', 'w') as file:
json.dump(data, file, indent=4)
從JSON文件讀取數(shù)據(jù)
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
5. 處理JSON與Python中的其他數(shù)據(jù)類型
Python中的某些數(shù)據(jù)類型在JSON中并沒有直接對應(yīng)的表示。例如,Python的set、tuple和complex類型。處理這些數(shù)據(jù)類型時(shí)需要特別注意。
轉(zhuǎn)換set和tuple
set和tuple需要轉(zhuǎn)換為list,因?yàn)镴SON格式不支持這兩種類型。
import json
data = {
"name": "Charlie",
"hobbies": {"reading", "sports"}, # set
"numbers": (1, 2, 3) # tuple
}
# 轉(zhuǎn)換 set 和 tuple
data['hobbies'] = list(data['hobbies'])
data['numbers'] = list(data['numbers'])
json_str = json.dumps(data, indent=4)
print(json_str)
轉(zhuǎn)換complex類型
complex類型需要轉(zhuǎn)換為字符串或其他可序列化的表示形式。
import json
data = {
"name": "David",
"number": complex(2, 3) # complex number
}
# 轉(zhuǎn)換 complex number
data['number'] = str(data['number'])
json_str = json.dumps(data, indent=4)
print(json_str)
處理JSON數(shù)據(jù)是Python開發(fā)中的常見任務(wù),Python的json模塊提供了強(qiáng)大的功能來方便地進(jìn)行JSON數(shù)據(jù)的編碼和解碼。掌握json.dumps()、json.loads()、json.dump()和json.load()等基本方法,可以幫助你高效地處理JSON數(shù)據(jù)。對于更復(fù)雜的數(shù)據(jù)類型或特定場景,需要對數(shù)據(jù)進(jìn)行適當(dāng)?shù)霓D(zhuǎn)換和處理。通過這些基本操作和技巧,你可以在Python中輕松地處理和交換JSON數(shù)據(jù)。