Python3實現(xiàn)的字典、列表和json對象互轉(zhuǎn)功能示例
本文實例講述了Python3實現(xiàn)的字典、列表和json對象互轉(zhuǎn)功能。分享給大家供大家參考,具體如下:
python3可以使用json模塊操作json
json.dumps(): 對json進行編碼,對應(yīng)php的json_encode()
json.loads(): 對json進行解碼,對應(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ī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函數(shù)的定義方式與函數(shù)參數(shù)問題實例分析
這篇文章主要介紹了Python函數(shù)的定義方式與函數(shù)參數(shù)問題,結(jié)合實例形式詳細分析了Python函數(shù)定義、函數(shù)參數(shù)相關(guān)原理、操作技巧與注意事項,需要的朋友可以參考下2019-12-12
如何用VScode配置Python開發(fā)環(huán)境
這篇文章主要介紹了如何用VScode配置Python開發(fā)環(huán)境,vscode有很多優(yōu)點,用VScode來編寫Python,也是相當(dāng)?shù)暮糜玫?需要的朋友可以參考下2023-03-03
Python數(shù)據(jù)分析之雙色球基于線性回歸算法預(yù)測下期中獎結(jié)果示例
這篇文章主要介紹了Python數(shù)據(jù)分析之雙色球基于線性回歸算法預(yù)測下期中獎結(jié)果,涉及Python基于線性回歸算法的數(shù)值運算相關(guān)操作技巧,需要的朋友可以參考下2018-02-02
Python中的enumerate函數(shù)使用方法詳解
enumerate()是python的內(nèi)置函數(shù),適用于python2.x和python3.x,這篇文章主要給大家介紹了關(guān)于Python中的enumerate函數(shù)使用方法的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-06-06

