在使用 Python 編碼或解碼 JSON 數據前,咱們須要先安裝 JSON 模塊。咱們會下載 Demjson 並安裝:python
$tar xvfz demjson-1.6.tar.gz $cd demjson-1.6 $python setup.py install
函數 | 描述 |
---|---|
encode | 將 Python 對象編碼成 JSON 字符串 |
decode | 將已編碼的 JSON 字符串解碼爲 Python 對象 |
Python encode() 函數用於將 Python 對象編碼成 JSON 字符串。web
demjson.encode(self, obj, nest_level=0)
如下實例將數組編碼爲 JSON 格式數據:json
#!/usr/bin/python import demjson data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] json = demjson.encode(data) print json
以上代碼執行結果爲:數組
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Python 可使用 demjson.decode() 函數解碼 JSON 數據。該函數返回 Python 字段的數據類型。函數
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
以上代碼執行結果爲:spa
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}