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)文章
PyCharm出現(xiàn)Error:Python?packaging?tool?'setuptools&apo
這篇文章主要給大家介紹了關(guān)于PyCharm出現(xiàn)Error:Python?packaging?tool?'setuptools'?not?found的解決辦法,文中通過圖文及代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12Python實戰(zhàn)之大魚吃小魚游戲的實現(xiàn)
這篇文章主要介紹了如何利用Python制作一個經(jīng)典游戲之大魚吃小魚,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Python有一定幫助,需要的可以參考一下2022-04-04Python中的time模塊與datetime模塊用法總結(jié)
Python中內(nèi)置的各項時間日期函數(shù)幾乎都來自于time和datetime這兩個模塊,下面整理了Python中的time模塊與datetime模塊用法總結(jié),需要的朋友可以參考下2016-06-06Python數(shù)據(jù)結(jié)構(gòu)隊列解決約瑟夫斯問題
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)隊列解決約瑟夫斯問題2023-02-02