python自动解析json_Python语言解析JSON详解
本文主要向大家介紹了Python語(yǔ)言解析JSON詳解,通過(guò)具體的內(nèi)容向大家展示,希望對(duì)大家學(xué)習(xí)Python語(yǔ)言有所幫助。
JSON 函數(shù)使用 JSON 函數(shù)需要導(dǎo)入 json 庫(kù):import json。函數(shù) 描述json.dumps 將 Python 對(duì)象編碼成 JSON 字符串json.loads 將已編碼的 JSON 字符串解碼為 Python 對(duì)象json.dumps語(yǔ)法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以上代碼執(zhí)行結(jié)果為:{"number": 6, "name": "Pythontab"}注意: 大家可能發(fā)現(xiàn),執(zhí)行上述轉(zhuǎn)換以后,數(shù)據(jù)并沒(méi)有發(fā)生變化,這里要說(shuō)一下: 在json中雙引號(hào)才是標(biāo)注的字符串分割符號(hào),單引號(hào)不標(biāo)準(zhǔn)。使用參數(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ì)照表:PythonJSONdictobjectlist, tuplearraystr, unicodestringint, long, floatnumberTruetrueFalsefalseNonenulljson.loadsjson.loads 用于解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。語(yǔ)法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以上代碼執(zhí)行結(jié)果為:{u'number': 6, u'name': u'Pythontab'}json 類型轉(zhuǎn)換到 python 的類型對(duì)照表:JSONPythonobjectdictarrayliststringunicodenumber (int)int, longnumber (real)floattrueTruefalseFalsenullNone使用第三方庫(kù):DemjsonDemjson 是 python 的第三方模塊庫(kù),可用于編碼和解碼 JSON 數(shù)據(jù),包含了 JSONLint 的格式化及校驗(yàn)功能。Github 地址:https://github.com/dmeranda/demjson環(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 DemjsonJSON 函數(shù)函數(shù) 描述encode 將 Python 對(duì)象編碼成 JSON 字符串decode 可以使用 demjson.decode() 函數(shù)解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。encode語(yǔ)法demjson.encode(self, obj, nest_level=0)decode語(yǔ)法demjson.decode(self, txt)使用都非常簡(jiǎn)單,我就不在這里舉例啦~~
本文由職坐標(biāo)整理并發(fā)布,希望對(duì)同學(xué)們學(xué)習(xí)Python有所幫助,更多內(nèi)容請(qǐng)關(guān)注職坐標(biāo)編程語(yǔ)言Python頻道!
總結(jié)
以上是生活随笔為你收集整理的python自动解析json_Python语言解析JSON详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 课堂经验值管理小程序_微信小程序怎么管理
- 下一篇: python换行不执行_PYTHON无法