Python對象與json數(shù)據(jù)的轉(zhuǎn)換問題實例詳解
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,易于人閱讀和編寫。
JSON 函數(shù)
使用 JSON 函數(shù)需要導(dǎo)入 json 庫:import json。
函數(shù) | 描述 |
---|---|
json.dumps | 將 Python 對象編碼成 JSON 字符串 |
json.loads | 將已編碼的 JSON 字符串解碼為 Python 對象 |
json.dumps
json.dumps 用于將 Python 對象編碼成 JSON 字符串。
語法
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
實例
以下實例將數(shù)組編碼為 JSON 格式數(shù)據(jù):
實例
#!/usr/bin/python import json data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] data2 = json.dumps(data) print(data2)
以上代碼執(zhí)行結(jié)果為:
[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]
使用參數(shù)讓 JSON 數(shù)據(jù)格式化輸出:
實例
#!/usr/bin/python import json data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] data2 = json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': ')) print(data2)
以上代碼執(zhí)行結(jié)果為:
{
"a": "Runoob",
"b": 7
}
python 原始類型向 json 類型的轉(zhuǎn)化對照表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
json.loads
json.loads 用于解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。
語法
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
實例
以下實例展示了Python 如何解碼 JSON 對象:
實例
#!/usr/bin/python import json jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; text = json.loads(jsonData) print(text)
以上代碼執(zhí)行結(jié)果為:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
json 類型轉(zhuǎn)換到 python 的類型對照表:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
更多內(nèi)容參考:https://docs.python.org/2/library/json.html。
使用第三方庫:Demjson
Demjson 是 python 的第三方模塊庫,可用于編碼和解碼 JSON 數(shù)據(jù),包含了 JSONLint 的格式化及校驗功能。
Github 地址:https://github.com/dmeranda/demjson
官方地址:http://deron.meranda.us/python/demjson/
環(huán)境配置
在使用 Demjson 編碼或解碼 JSON 數(shù)據(jù)前,我們需要先安裝 Demjson 模塊。本教程我們會下載 Demjson 并安裝:
$ tar -xvzf demjson-2.2.3.tar.gz $ cd demjson-2.2.3 $ python setup.py install
更多安裝介紹查看:http://deron.meranda.us/python/demjson/install
JSON 函數(shù)
函數(shù) | 描述 |
---|---|
encode | 將 Python 對象編碼成 JSON 字符串 |
decode | 將已編碼的 JSON 字符串解碼為 Python 對象 |
encode
Python encode() 函數(shù)用于將 Python 對象編碼成 JSON 字符串。
語法
demjson.encode(self, obj, nest_level=0)
實例
以下實例將數(shù)組編碼為 JSON 格式數(shù)據(jù):
實例
#!/usr/bin/python import demjson data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] json = demjson.encode(data) print(json)
以上代碼執(zhí)行結(jié)果為:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
decode
Python 可以使用 demjson.decode() 函數(shù)解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。
語法
demjson.decode(self, txt)
實例
以下實例展示了Python 如何解碼 JSON 對象:
實例
#!/usr/bin/python import demjson json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; text = demjson.decode(json) print(text)
以上代碼執(zhí)行結(jié)果為:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
測試程序:
import json #json_data = [{"蘋果":"appale","香蕉":"banana"}, # {"貓":"cat","狗":"dog"}, # {"紅色":"red","藍(lán)色":"blue"},] #python數(shù)據(jù)類型: list json_data = [{"a":"appale","b":"banana"}, {"c":"cat","d":"dog"}, {"r":"red","b":"blue"},] print(json_data) #[{'a': 'appale', 'b': 'banana'}, {'c': 'cat', 'd': 'dog'}, {'r': 'red', 'b': 'blue'}] print(type(json_data))#<class 'list'> json_data2 = json.dumps(json_data)#json.dumps 用于將 Python 對象編碼成 JSON 字符串。 print(json_data2) #[{"a": "appale", "b": "banana"}, {"c": "cat", "d": "dog"}, {"r": "red", "b": "blue"}] print(type(json_data2))#<class 'str'> site = { "sites": [ { "name":"腳本之家" , "url":"www.dbjr.com.cn" }, { "name":"google" , "url":"www.google.com" }, { "name":"微博" , "url":"www.weibo.com" } ] } #print(sites) #NameError: name 'sites' is not defined print(site['sites'])
到此這篇關(guān)于Python對象與json數(shù)據(jù)的轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)Python對象轉(zhuǎn)換json數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 文件操作之讀取文件(read),文件指針與寫入文件(write),文件打開方式示例
這篇文章主要介紹了Python 文件操作之讀取文件(read),文件指針與寫入文件(write),文件打開方式,結(jié)合實例形式分析了Python文件讀寫相關(guān)的指針、打開方式等相關(guān)操作技巧,需要的朋友可以參考下2019-09-09DataFrame 數(shù)據(jù)合并實現(xiàn)(merge,join,concat)
這篇文章主要介紹了DataFrame 數(shù)據(jù)合并實現(xiàn)(merge,join,concat),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06pytorch之關(guān)于PyTorch結(jié)構(gòu)介紹
這篇文章主要介紹了pytorch之關(guān)于PyTorch結(jié)構(gòu)的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09