Python JSON
本章節我們將為大家介紹如何使用Python 語言來編碼和解碼JSON 對象。
環境配置
在使用Python 編碼或解碼JSON 數據前,我們需要先安裝JSON 模塊。 本教程我們會下載Demjson並安裝:
$ tar xvfz demjson-1.6.tar.gz $ cd demjson-1.6 $ python setup.py install
JSON 函數
函數 | 描述 |
---|---|
encode | 將Python 對象編碼成JSON 字符串 |
decode | 將已編碼的JSON 字符串解碼為Python 對象 |
encode
Python encode() 函數用於將Python 對象編碼成JSON 字符串。
語法
demjson.encode(self, obj, nest_level=0)
實例
以下實例將數組編碼為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}]
decode
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
以上代碼執行結果為:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}