python素材库_python的JSON库
標(biāo)簽:mingw???mini???mic???int???module???als???str???lease???函數(shù)
JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式,易于人閱讀和編寫。
1.json庫的使用
使用 JSON 函數(shù)需要導(dǎo)入 json 庫:import json。
函數(shù)
描述
json.dumps
將 Python 對(duì)象編碼成 JSON 字符串
json.loads
將已編碼的 JSON 字符串解碼為 Python 對(duì)象
1. json.dumps? ?將 Python 對(duì)象編碼成 JSON 字符串。
語法
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)
例如:將python數(shù)組對(duì)象轉(zhuǎn)為JSON字符串
#!/usr/bin/python
importjson
data= [ { ‘a(chǎn)‘ : 1, ‘b‘ : 2, ‘c‘ : 3, ‘d‘ : 4, ‘e‘ : 5} ]
json=json.dumps(data)print json
結(jié)果:
[{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]
例如:讓JSON數(shù)據(jù)格式化輸出:
importjsonprint(json.dumps({‘a(chǎn)‘: ‘china‘, ‘b‘: 7}, sort_keys=True, indent=4, separators=(‘,‘, ‘:‘)))
結(jié)果:
{
"a": "china",
"b": 7
}
python 原始類型向 json 類型的轉(zhuǎn)化對(duì)照表:
Python
JSON
dict
object
list, tuple
array
str, unicode
string
int, long, float
number
True
true
False
false
None
null
2. 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]]]]]]]])
例如:JSON字符串轉(zhuǎn)py對(duì)象
#!/usr/bin/python
importjson
jsonData= ‘{"name":"張三","age":20,"sex":"男"}‘;
text=json.loads(jsonData)print(text)
結(jié)果
{‘name‘: ‘張三‘, ‘a(chǎn)ge‘: 20, ‘sex‘: ‘男‘}
json 類型轉(zhuǎn)換到 python 的類型對(duì)照表:
JSON
Python
object
dict
array
list
string
unicode
number (int)
int, long
number (real)
float
true
True
false
False
null
None
2.? ?Demjson第三方庫的使用
Demjson 是 python 的第三方模塊庫,可用于編碼和解碼 JSON 數(shù)據(jù),包含了 JSONLint 的格式化及校驗(yàn)功能。
1.? 安裝模塊
(1)下載
https://github.com/dmeranda/demjson
(2)解壓后安裝
$ pwd/c/Users/Administrator/Desktop/pytest/pymodule/demjson-release-2.2.4Administrator@MicroWin10-1535 MINGW64 ~/Desktop/pytest/pymodule/demjson-release-2.2.4$ python setup.py install
2.? ?JSON 函數(shù)
函數(shù)
描述
encode
將 Python 對(duì)象編碼成 JSON 字符串
decode
將已編碼的 JSON 字符串解碼為 Python 對(duì)象
(1)??encode() 函數(shù)用于將 Python 對(duì)象編碼成 JSON 字符串。
語法
demjson.encode(self, obj, nest_level=0)
例如:
#!/usr/bin/python
importdemjson
data= [ { ‘a(chǎn)‘ : 1, ‘b‘ : 2, ‘c‘ : 3, ‘d‘ : 4, ‘e‘ : 5} ]
json=demjson.encode(data)print(json)
結(jié)果:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
(2)demjson.decode() 函數(shù)解碼 JSON 數(shù)據(jù)。該函數(shù)返回 Python 字段的數(shù)據(jù)類型。
語法:
demjson.decode(self, txt)
例如:將json字符串轉(zhuǎn)為JSON對(duì)象:
#!/usr/bin/python
importdemjson
jsonData= ‘{"name":"張三","age":20,"sex":"男"}‘;
obj=demjson.decode(jsonData)print(obj)print(type(obj))
結(jié)果:
{‘name‘: ‘張三‘, ‘a(chǎn)ge‘: 20, ‘sex‘: ‘男‘}
python的JSON庫
標(biāo)簽:mingw???mini???mic???int???module???als???str???lease???函數(shù)
總結(jié)
以上是生活随笔為你收集整理的python素材库_python的JSON库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 类属性的特征java_java定义类、属
- 下一篇: java 加减乘除 工具类_Java数学