本章節(jié)我們將為大家介紹如何使用 Python 語言來編碼和解碼 JSON 對象。環(huán)境配置在使用 Python 編碼或解碼 JSON 數(shù)據(jù)前,我們需要先安裝 JSON 模塊。本教程我們會下載 Demjson 并安裝: $ tar xvfz demjson-1.6.tar.gz $ cd demjson-1.6 $ python setup.py install JSON 函數(shù)
encodePython encode() 函數(shù)用于將 Python 對象編碼成 JSON 字符串。 語法demjson.encode(self, obj, nest_level=0) 實例以下實例將數(shù)組編碼為 JSON 格式數(shù)據(jù): #!/usr/bin/python import demjson data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] json = demjson.encode(data) print json 以上代碼執(zhí)行結(jié)果為: [{"a":1,"b":2,"c":3,"d":4,"e":5}] decodePython 可以使用 demjson.decode() 函數(shù)解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。 語法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 以上代碼執(zhí)行結(jié)果為: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4} |
|