国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Python JSON

本章節(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ù)

函數(shù)描述
encode將 Python 對象編碼成 JSON 字符串
decode將已編碼的 JSON 字符串解碼為 Python 對象

encode

Python 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}]

decode

Python 可以使用 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}