本文實(shí)例講述了Python3實(shí)現(xiàn)的字典、列表和json對(duì)象互轉(zhuǎn)功能。分享給大家供大家參考,具體如下:
python3可以使用json模塊操作json
json.dumps(): 對(duì)json進(jìn)行編碼,對(duì)應(yīng)php的json_encode()
json.loads(): 對(duì)json進(jìn)行解碼,對(duì)應(yīng)php的json_decode()
test.py
#!/usr/bin/python3import json#python字典類型轉(zhuǎn)換為json對(duì)象data = { 'id' : 1, 'name' : 'test1', 'age' : '1'}data2 = [{ 'id' : 1, 'name' : 'test1', 'age' : '1'},{ 'id' : 2, 'name' : 'test2', 'age' : '2'}]json_str = json.dumps(data)print ("python原始數(shù)據(jù):", repr(data))print ("json對(duì)象:", json_str)json_str2 = json.dumps(data2)print ("python原始數(shù)據(jù):", repr(data2))print ("json對(duì)象:", json_str2)# 將json對(duì)象轉(zhuǎn)換為python字典data3 = json.loads(json_str)print ("data3['name']: ", data3['name'])print ("data3['age']: ", data3['age'])執(zhí)行結(jié)果
[root@mail pythonCode]# python3 test.py
python原始數(shù)據(jù): {'id': 1, 'name': 'test1', 'age': '1'}
json對(duì)象: {"id": 1, "name": "test1", "age": "1"}
python原始數(shù)據(jù): [{'id': 1, 'name': 'test1', 'age': '1'}, {'id': 2, 'name': 'test2', 'age': '2'}]
json對(duì)象: [{"id": 1, "name": "test1", "age": "1"}, {"id": 2, "name": "test2", "age": "2"}]
data3['name']: test1
data3['age']: 1
PS:關(guān)于json操作,這里再為大家推薦幾款比較實(shí)用的json在線工具供大家參考使用:
在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat
在線json壓縮/轉(zhuǎn)義工具:
http://tools.jb51.net/code/json_yasuo_trans
更多Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作json技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選