Json簡介:Json申尤,全名 JavaScript Object Notation滚粟,是一種輕量級的數(shù)據(jù)交換格式寻仗。最廣泛的應(yīng)用是作為AJAX中web服務(wù)器和客戶端的通訊的數(shù)據(jù)格式。
Python2.6及以上的版本可以直接import json
進(jìn)行使用凡壤,不需要下載json包了署尤。
json模塊支持python的大部分內(nèi)置類型與Json進(jìn)行轉(zhuǎn)換。
json模塊提供了四個(gè)方法
dumps #encode,將python對象轉(zhuǎn)換為json對象
loads #decode,將json對象轉(zhuǎn)換為python對象
dump #encode,將python對象轉(zhuǎn)換為可以存儲到文件的fp文件流
load #decode,將fp文件流轉(zhuǎn)換為python對象
Encode過程亚侠,是把python對象轉(zhuǎn)換成json對象的一個(gè)過程曹体,常用的兩個(gè)函數(shù)是dumps和dump函數(shù)。兩個(gè)函數(shù)的唯一區(qū)別就是dump把python對象轉(zhuǎn)換成json對象生成一個(gè)fp的文件流硝烂,而dumps則是生成了一個(gè)所有程序語言都認(rèn)識的字符串箕别。
Decode過程,是把json對象轉(zhuǎn)換成python對象的一個(gè)過程滞谢,常用的兩個(gè)函數(shù)是loads和load函數(shù)串稀。區(qū)別跟dump和dumps是一樣的。
來看看他們的參數(shù)
json.dump(obj, fp, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, default, **kw)
json.dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, default, **kw)
json.load(fp, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
json.loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
dumps接受一個(gè)python對象作為必須參數(shù)(其他參數(shù)可選)爹凹,而這個(gè)對象可以是任何python的數(shù)據(jù)類型厨诸。
data = ['username','age','others']
print type(data)
test = json.dumps(data)
print type(test)
print test
print ''
data1 = (1,2,3)
print type(data1)
test1 = json.dumps(data1)
print type(test1)
print test1
print ''
data2 = {"user":"whaike","age":24}
print type(data2)
test2 = json.dumps(data2)
print type(test2)
print test2
print ''
data3 = "what fuck ..."
print type(data3)
test3 = json.dumps(data3)
print type(test3)
print test3
print ''
data4 = None
print type(data4)
test4 = json.dumps(data4)
print type(test4)
print test4
#結(jié)果
#<type 'list'>
#<type 'str'>
#["username", "age", "others"]
#
#<type 'tuple'>
#<type 'str'>
#[1, 2, 3]
#
#<type 'dict'>
#<type 'str'>
#{"age": 24, "user": "whaike"}
#
#<type 'str'>
#<type 'str'>
#"what fuck ..."
#
#<type 'NoneType'>
#<type 'str'>
#null
其他就不列舉了镶殷,詳細(xì)如下(python -> json)
而loads與其相反,將json編碼的字符串再轉(zhuǎn)換為python的數(shù)據(jù)結(jié)構(gòu)禾酱。詳細(xì)如下(json ->python)
其他常用參數(shù)說明:
Skipkeys:默認(rèn)值是False,如果dict的keys內(nèi)的數(shù)據(jù)不是python的基本類型(str,unicode,int,long,float,bool,None)绘趋,設(shè)置為False時(shí)颤陶,就會(huì)報(bào)TypeError的錯(cuò)誤。此時(shí)設(shè)置成True陷遮,則會(huì)跳過這類key滓走。
ensure_ascii:默認(rèn)值True,如果dict內(nèi)含有non-ASCII的字符帽馋,則會(huì)類似\uXXXX的顯示數(shù)據(jù)搅方,設(shè)置成False后,就能正常顯示绽族。
indent:應(yīng)該是一個(gè)非負(fù)的整型姨涡,如果是0,或者為空吧慢,則一行顯示數(shù)據(jù)涛漂,否則會(huì)換行且按照indent的數(shù)量顯示前面的空白,這樣打印出來的json數(shù)據(jù)也叫pretty-printed json。
separators:分隔符匈仗,實(shí)際上是(item_separator, dict_separator)的一個(gè)元組瓢剿,默認(rèn)的就是(',',':');這表示dictionary內(nèi)keys之間用“,”隔開悠轩,而KEY和value之間用“:”隔開间狂。
encoding:默認(rèn)是UTF-8,設(shè)置json數(shù)據(jù)的編碼方式哗蜈。
sort_keys:將數(shù)據(jù)根據(jù)keys的值進(jìn)行排序前标。
部分學(xué)習(xí)代碼片段
dic1 = {'type':'dic1','username':'loleina','age':16}
json_dic1 = json.dumps(dic1)
print json_dic1
json_dic2 = json.dumps(dic1,sort_keys=True,indent =4,separators=(',', ': '),encoding="gbk",ensure_ascii=True )
print json_dic2
#結(jié)果
#{"username": "loleina", "age": 16, "type": "dic1"}
#{
# "age": 16,
# "type": "dic1",
# "username": "loleina"
#}
如果把實(shí)例中的key'username'的value換成中文的“測試”,
dic1 = {'type':'dic1','username':'測試','age':16}
json_dic1 = json.dumps(dic1)
print json_dic1
json_dic2 = json.dumps(dic1,sort_keys=True,indent =4,separators=(',', ': '),encoding="utf8",ensure_ascii=False )
print json_dic2
#結(jié)果
#{"username": "\u6d4b\u8bd5", "age": 16, "type": "dic1"}
#{
# "age": 16,
# "type": "dic1",
# "username": "測試"
#}
# dump功能
# 將數(shù)據(jù)通過特殊的形式轉(zhuǎn)換為所有程序語言都認(rèn)識的字符串,并寫入文件
with open('D:/tmp.json', 'w') as f:
json.dump(data, f)
# load功能
# 從數(shù)據(jù)文件中讀取數(shù)據(jù),并將json編碼的字符串轉(zhuǎn)換為python的數(shù)據(jù)結(jié)構(gòu)
with open('D:/tmp.json', 'r') as f:
data = json.load(f)
參考如下距潘,侵刪
python對json的操作總結(jié)
python---Json
官網(wǎng)json— JSON encoder and decode