Python 中的 JSON



本章介紹如何使用 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 物件。

Python 中的 JSON 編碼(encode)

Python encode() 函式將 Python 物件編碼為 JSON 字串表示。

語法

demjson.encode(self, obj, nest_level=0)

示例

以下示例顯示 Python 中 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 中的 JSON 解碼(decode)

Python 可以使用 demjson.decode() 函式解碼 JSON。此函式將從 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}
廣告
© . All rights reserved.