W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
JSON (JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式。它基于 ECMAScript 的一個(gè)子集。
Python3 中可以使用 json 模塊來(lái)對(duì) JSON 數(shù)據(jù)進(jìn)行編解碼,它包含了兩個(gè)函數(shù):
在json的編解碼過(guò)程中,Python 的原始類型與 json 類型會(huì)相互轉(zhuǎn)換,具體的轉(zhuǎn)化對(duì)照如下:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
以下實(shí)例演示了 Python 數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)換為 JSON:
#!/usr/bin/python3
import json
# Python 字典類型轉(zhuǎn)換為 JSON 對(duì)象
data = {
'no' : 1,
'name' : 'W3CSchool',
'url' : 'http://www.o2fo.com'
}
json_str = json.dumps(data)
print ("Python 原始數(shù)據(jù):", repr(data))
print ("JSON 對(duì)象:", json_str)
執(zhí)行以上代碼輸出結(jié)果為:
Python 原始數(shù)據(jù): {'url': 'http://www.o2fo.com', 'no': 1, 'name': 'W3CSchool'}
JSON 對(duì)象: {"url": "http://www.o2fo.com", "no": 1, "name": "W3CSchool"}
通過(guò)輸出的結(jié)果可以看出,簡(jiǎn)單類型通過(guò)編碼后跟其原始的repr()輸出結(jié)果非常相似。
接著以上實(shí)例,我們可以將一個(gè)JSON編碼的字符串轉(zhuǎn)換回一個(gè)Python數(shù)據(jù)結(jié)構(gòu):
#!/usr/bin/python3
import json
# Python 字典類型轉(zhuǎn)換為 JSON 對(duì)象
data1 = {
'no' : 1,
'name' : 'W3CSchool',
'url' : 'http://www.o2fo.com'
}
json_str = json.dumps(data1)
print ("Python 原始數(shù)據(jù):", repr(data1))
print ("JSON 對(duì)象:", json_str)
# 將 JSON 對(duì)象轉(zhuǎn)換為 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])
執(zhí)行以上代碼輸出結(jié)果為:
ython 原始數(shù)據(jù): {'name': 'W3CSchool', 'no': 1, 'url': 'http://www.o2fo.com'}
JSON 對(duì)象: {"name": "W3CSchool", "no": 1, "url": "http://www.o2fo.com"}
data2['name']: W3CSchool
data2['url']: http://www.o2fo.com
如果你要處理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 來(lái)編碼和解碼 JSON 數(shù)據(jù)。例如:
# 寫(xiě)入 JSON 數(shù)據(jù)
with open('data.json', 'w') as f:
json.dump(data, f)
# 讀取數(shù)據(jù)
with open('data.json', 'r') as f:
data = json.load(f)
更多資料請(qǐng)參考:https://docs.python.org/3/library/json.html
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: