Python3實現(xiàn)的字典、列表和json對象互轉(zhuǎn)功能示例
本文實例講述了Python3實現(xiàn)的字典、列表和json對象互轉(zhuǎn)功能。分享給大家供大家參考,具體如下:
python3可以使用json模塊操作json
json.dumps()
: 對json進(jìn)行編碼,對應(yīng)php的json_encode()
json.loads()
: 對json進(jìn)行解碼,對應(yīng)php的json_decode()
test.py
#!/usr/bin/python3 import json #python字典類型轉(zhuǎn)換為json對象 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對象:", json_str) json_str2 = json.dumps(data2) print ("python原始數(shù)據(jù):", repr(data2)) print ("json對象:", json_str2) # 將json對象轉(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對象: {"id": 1, "name": "test1", "age": "1"}
python原始數(shù)據(jù): [{'id': 1, 'name': 'test1', 'age': '1'}, {'id': 2, 'name': 'test2', 'age': '2'}]
json對象: [{"id": 1, "name": "test1", "age": "1"}, {"id": 2, "name": "test2", "age": "2"}]
data3['name']: test1
data3['age']: 1
PS:關(guān)于json操作,這里再為大家推薦幾款比較實用的json在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
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文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
- Python3 json模塊之編碼解碼方法講解
- Python3中對json格式數(shù)據(jù)的分析處理
- Python3自定義json逐層解析器代碼
- python3實現(xiàn)從kafka獲取數(shù)據(jù),并解析為json格式,寫入到mysql中
- python3 實現(xiàn)的對象與json相互轉(zhuǎn)換操作示例
- python3 json數(shù)據(jù)格式的轉(zhuǎn)換(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互轉(zhuǎn)換)
- Python3爬蟲爬取百姓網(wǎng)列表并保存為json功能示例【基于request、lxml和json模塊】
- Python3實現(xiàn)將本地JSON大數(shù)據(jù)文件寫入MySQL數(shù)據(jù)庫的方法
- 解決python3 json數(shù)據(jù)包含中文的讀寫問題
- Python3內(nèi)置json模塊編碼解碼方法詳解
相關(guān)文章
python中Matplotlib實現(xiàn)繪制3D圖的示例代碼
本篇文章主要介紹了python中Matplotlib實現(xiàn)繪制3D圖的示例代碼,具有一定的參考價值,有興趣的可以了解一下2017-09-09python pip安裝包出現(xiàn):Failed building wheel for xxx錯誤的解決
今天小編就為大家分享一篇python pip安裝包出現(xiàn):Failed building wheel for xxx錯誤的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12Python Pandas實現(xiàn)數(shù)據(jù)分組求平均值并填充nan的示例
今天小編就為大家分享一篇Python Pandas實現(xiàn)數(shù)據(jù)分組求平均值并填充nan的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07python使用xauth方式登錄飯否網(wǎng)然后發(fā)消息
這篇文章主要介紹了python使用xauth方式登錄飯否網(wǎng)然后發(fā)消息示例,需要的朋友可以參考下2014-04-04Python + OpenCV 實現(xiàn)LBP特征提取的示例代碼
這篇文章主要介紹了Python + OpenCV 實現(xiàn)LBP特征提取的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07