json.dumps():將 Python 對象編碼成 JSON 字符串, dic -> json strhtml
json.dump() :將 Python 對象保存成 JSON 字符串格式到文件中。python
json.loads() :將已編碼的 JSON 字符串解碼爲 Python 對象, json str -> dicgit
json.load() :從文件中讀取json數據 github
若是dic中的key不是string類型,編碼的時候會變成string類型。因此編碼以後再解碼,獲得的結果可能和原始數據不一樣。json
JSON必須使用雙引號來包裹字符串,而不能使用單引號。若是在字符串中出現引號能夠加上轉義字符\ 。數組
對象和數組很關鍵的一個區別就是,對象是 「名稱--值「對 構成的列表或集合,數組是 值 構成的列表或集合;還有一點就是數組中全部的值應該具備相同的數據類型。函數
import json
# json.dumps() In [67]: list1 = [{'a': 1, 'a2': 2, 'a3': 3}, {'c': [111,222,333]}, {'b': 11}] In [68]: jstr1 = json.dumps(list1) In [69]: jstr2 = json.dumps(list1,sort_keys=True, indent=4) In [70]: print jstr1 [{"a": 1, "a3": 3, "a2": 2}, {"c": [111, 222, 333]}, {"b": 11}] In [71]: print jstr2 [ { "a": 1, "a2": 2, "a3": 3 }, { "c": [ 111, 222, 333 ] }, { "b": 11 } ] # json.dump() In [72]: f = open('./jstr.txt','w+') In [73]: json.dump(list1,f,indent=4) #json.dump(x,f),x是對象,f是一個文件對象,這個方法能夠將json字符串寫入到文本文件中。 In [74]: f.close() In [75]: cat jstr.txt [ { "a": 1, "a3": 3, "a2": 2 }, { "c": [ 111, 222, 333 ] }, { "b": 11 } ] # json.loads() In [76]: json.loads(jstr1) Out[76]: [{u'a': 1, u'a2': 2, u'a3': 3}, {u'c': [111, 222, 333]}, {u'b': 11}] # json.load() In [77]: f2 = open('./jstr.txt','r+') In [78]: result = json.load(f2) In [79]: result Out[79]: [{u'a': 1, u'a2': 2, u'a3': 3}, {u'c': [111, 222, 333]}, {u'b': 11}]
1. json.dump
(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)¶this
2. json.dumps
(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)¶編碼
3. json.load
(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)spa
4. json.loads
(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶
python 原始類型向 json 類型的轉化對照表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
json 類型轉換到 python 的類型對照表:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
Demjson 是 python 的第三方模塊庫,可用於編碼和解碼 JSON 數據,包含了 JSONLint 的格式化及校驗功能。
Github 地址:https://github.com/dmeranda/demjson
官方地址:http://deron.meranda.us/python/demjson/
安裝:pip install demjson
demjson.encode()
demjson.encode_to_file()
demjson.decode()
demjson.decode_file()
1. 編碼成JSON格式
In [155]: import demjson In [156]: d1 = [{'1':1,'4':4,'2':2,'5':5,'3':3}] In [157]: d2 = [{'c':2,'a':5,'b':3}] In [158]: demjson.encode(d1) Out[158]: u'[{"1":1,"2":2,"3":3,"4":4,"5":5}]' In [159]: demjson.encode_to_file('f1.txt',d1) In [160]: cat f1.txt [{"1":1,"2":2,"3":3,"4":4,"5":5}] In [161]: demjson.encode_to_file('f1.txt',d2,overwrite=True) In [162]: cat f1.txt [{"a":5,"b":3,"c":2}]
2. 解碼成Python對象
In [172]: jstr = '{"a":1,"d":4,"c":3,"b":2}' In [173]: demjson.decode(jstr) Out[173]: {u'a': 1, u'b': 2, u'c': 3, u'd': 4} In [174]: cat f2.txt {"a":1,"d":4,"c":3,"b":[2,3,4]} In [175]: demjson.decode_file('f2.txt') Out[175]: {u'a': 1, u'b': [2, 3, 4], u'c': 3, u'd': 4}
3. 檢查JSON格式
In [209]: c = demjson.jsonlint() #jsonlint是demjson中的一個類 In [210]: cat f2.txt {"a":1,"d":4,"c":3,"b":[2,3,4]} In [211]: c.main(['f2.txt']) #若是格式正確,則返回0 f2.txt: ok #說明是正確的JSON格式 Out[211]: 0 In [212]: cat f1.txt {1:11,2:22} In [213]: c.main(['f1.txt']) f1.txt:1:1: Warning: JSON only permits string literals as object properties (keys) | At line 1, column 1, offset 1 | Object started at line 1, column 0, offset 0 (AT-START) f1.txt:1:6: Warning: JSON only permits string literals as object properties (keys) | At line 1, column 6, offset 6 | Object started at line 1, column 0, offset 0 (AT-START) f1.txt: ok, with warnings Out[213]: 1 In [214]: c.main(['--help']) #查看幫助文檔,注意這裏是list,而且注意參數順序
4. 格式化輸出:
In [245]: c = demjson.jsonlint() In [246]: c.main(["-f","f2.txt"]) #-f | --format Reformat the JSON text (if conforming) to stdout { "a" : 1, "b" : [ 2, 3, 4 ], "c" : 3, "d" : 4 } Out[246]: 0
In [253]: c.main(["-f","-o","obj.txt","f2.txt"]) #-o filename | --output filename The filename to which reformatted JSON is to be written.
Out[253]: 0
In [254]: cat obj.txt { "a" : 1, "b" : [ 2, 3, 4 ], "c" : 3, "d" : 4 }