在使用 Python 編碼或解碼 JSON 數(shù)據(jù)前,我們需要先安裝 JSON 模塊。本教程我們會下載 Demjson 并安裝:
$ tar xvfz demjson-1.6.tar.gz$ cd demjson-1.6$ python setup.py install
函數(shù) | 描述 |
---|---|
encode | 將 Python 對象編碼成 JSON 字符串 |
decode | 將已編碼的 JSON 字符串解碼為 Python 對象 |
Python encode() 函數(shù)用于將 Python 對象編碼成 JSON 字符串。
demjson.encode(self, obj, nest_level=0)
以下實例將數(shù)組編碼為 JSON 格式數(shù)據(jù):
#!/usr/bin/pythonimport demjsondata = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]json = demjson.encode(data)print json
以上代碼執(zhí)行結果為:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Python 可以使用 demjson.decode() 函數(shù)解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。
demjson.decode(self, txt)
以下實例展示了Python 如何解碼 JSON 對象:
#!/usr/bin/pythonimport demjsonjson = '{"a":1,"b":2,"c":3,"d":4,"e":5}';text = demjson.decode(json)print text
以上代碼執(zhí)行結果為:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}