新聞中心
JSON 函數(shù)

使用 JSON 函數(shù)需要導(dǎo)入 json 庫:import json。
函數(shù)描述
json.dumps 將 Python 對(duì)象編碼成 JSON 字符串
json.loads 將已編碼的 JSON 字符串解碼為 Python 對(duì)象
json.dumps
語法
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
實(shí)例
以下實(shí)例將數(shù)組編碼為 JSON 格式數(shù)據(jù):
#!/usr/bin/python
import json
data = {'number': 6, 'name': 'Pythontab'}
jsonData = json.dumps(data)
print jsonData輸出結(jié)果為
{"number": 6, "name": "Pythontab"}使用參數(shù)讓 JSON 數(shù)據(jù)排序并格式化輸出:
#!/usr/bin/python
import json
data = {'number': 6, 'name': 'Pythontab'}
jsonData = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
print jsonData輸出結(jié)果
{
"name": "Pythontab",
"number": 6
}python 原始類型向 json 類型的轉(zhuǎn)化對(duì)照表:
json.loads
json.loads 用于解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。
語法
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
實(shí)例
以下實(shí)例展示了Python 如何解碼 JSON 對(duì)象:
#!/usr/bin/python
import json
jsonData = '{"number": 6, "name": "Pythontab"}'
str = json.loads(jsonData)
print str輸出結(jié)果
{u'number': 6, u'name': u'Pythontab'}json 類型轉(zhuǎn)換到 python 的類型對(duì)照表:
使用第三方庫:Demjson
Demjson 是 python 的第三方模塊庫,可用于編碼和解碼 JSON 數(shù)據(jù),包含了 JSONLint 的格式化及校驗(yàn)功能。
環(huán)境配置
在使用 Demjson 編碼或解碼 JSON 數(shù)據(jù)前,我們需要先安裝 Demjson 模塊。
方法1:源碼安裝
$ tar -xvzf demjson-2.2.4.tar.gz
$ cd demjson-2.2.4
$ python setup.py install
方法2:直接使用pip安裝
pip install Demjson
JSON函數(shù)
函數(shù)描述
encode 將 Python 對(duì)象編碼成 JSON 字符串
decode 可以使用 demjson.decode() 函數(shù)解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。
encode語法
demjson.encode(self, obj, nest_level=0)
decode語法
demjson.decode(self, txt)
當(dāng)前標(biāo)題:創(chuàng)新互聯(lián)Python教程:深入解析如何在Python中使用JSON
網(wǎng)站地址:http://www.dlmjj.cn/article/djdgpgo.html


咨詢
建站咨詢
