Python操作json的方法實例分析
本文實例講述了Python操作json的方法。分享給大家供大家參考,具體如下:
python中對json操作方法有兩種,解碼loads()和編碼dumps()
簡單來說:
import json dicts = json.loads() #loads()方法,將json串解碼為python對象,字典 json = json.dumps(dicts) #dumps()方法,將python字典編碼為json串
簡單例子:
>>> import json
>>> dicts = {'name':'test','type':[{'happy':'fish'},{'sad':'man'}]} #python的字典
>>> print(dicts.keys()) #python的字典可以通過內(nèi)置的字典方法操作keys 和values
dict_keys(['type', 'name'])
>>> print(dicts['name'])
test
>>> print(dicts['type'][0]['happy'])
fish
>>> print(dicts['type'][1]['sad'])
man
>>> j = json.dumps(dicts) #通過dumps()方法,將python字典編碼為json串
>>> j
'{"type": [{"happy": "fish"}, {"sad": "man"}], "name": "test"}'
>>> print(j['name']) #json不能通過字典方法獲取keys 和 values了。
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print(j['name'])
TypeError: string indices must be integers
更多的信息,可以參考python內(nèi)部的json文檔:
python>>> help(json)
如下圖所示:

或者官方文檔:
http://docs.python.org/library/json.html#module-json
PS:這里再為大家推薦幾款比較實用的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è)計有所幫助。
相關(guān)文章
OpenCV圖像識別之姿態(tài)估計Pose?Estimation學(xué)習(xí)
這篇文章主要為大家介紹了OpenCV圖像識別之姿態(tài)估計Pose?Estimation學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
numpy的Fancy Indexing和array比較詳解
這篇文章主要介紹了numpy的Fancy Indexing和array比較詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
python實現(xiàn)將文本轉(zhuǎn)換成語音的方法
這篇文章主要介紹了python實現(xiàn)將文本轉(zhuǎn)換成語音的方法,涉及Python中pyTTS模塊的相關(guān)使用技巧,需要的朋友可以參考下2015-05-05
如何將Pycharm中Terminal使用Powershell作為終端
這篇文章主要介紹了如何將Pycharm中Terminal使用Powershell作為終端問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

