在處理 JSON 數(shù)據(jù)時(shí),encode()
和 decode()
在 JSON 模塊中具有特定的含義和功能:
json.encode(obj)
:將 Python 對象(字典、列表等)編碼為 JSON 格式的字符串。
obj
:要進(jìn)行編碼的 Python 對象。
json.decode(json_string)
:將 JSON 格式的字符串解碼為 Python 對象。
json_string
:要進(jìn)行解碼的 JSON 字符串。
簡而言之,encode()
用于將 Python 對象編碼為 JSON 字符串,而 decode()
用于將 JSON 字符串解碼為 Python 對象。
下面是一個(gè)示例,展示了如何使用 encode()
和 decode()
進(jìn)行 JSON 編碼和解碼:
import json
# Python 對象轉(zhuǎn)為 JSON 字符串
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(data)
print(json_string) # {"name": "John", "age": 30, "city": "New York"}
# JSON 字符串解碼為 Python 對象
parsed_data = json.loads(json_string)
print(parsed_data) # {'name': 'John', 'age': 30, 'city': 'New York'}
在上述示例中,首先使用 dumps()
將 Python 對象 data
編碼為 JSON 字符串 json_string
。然后,使用 loads()
將 JSON 字符串 json_string
解碼為 Python 對象 parsed_data
。最終,通過打印輸出可以看到編碼和解碼操作的結(jié)果。
需要注意的是,encode()
和 decode()
在 JSON 模塊中的具體方法名是 dumps()
和 loads()
。這里的命名與一般的編碼/解碼函數(shù)有所不同,但它們的作用和功能相同。