python内置模块之json模块

json是一种轻量级的数据交换格式

python3中json模块提供有两个函数
json.dumps():对数据进行编码
json.loads():对数据进行解码

python编码成json类型转换对应表

python json
dict object
list,tuple array
str string
int,float,int number
True true
False flase
None null

json解码为python类型转换对应表

json python
object dict
array list
string str
number(int) int
number(real) float
true True
false False
none None

编码 和 解码演示

import json

dict1 = {'name': 'fengling', 'age': 18, 'sex': '男'}
json1 = json.dumps(dict1)
print(json1)
print(type(json1))

json2 = json1
dict2 = json.loads(json2)
print(dict2)
print(type(dict2))

执行结果:

{"name": "fengling", "age": 18, "sex": "\u7537"}
<class 'str'>
{'name': 'fengling', 'age': 18, 'sex': '男'}
<class 'dict'>

介绍两个常用属性

ensure_ascii= 值为False表示原样输出
indent = 0 表示美化输出

import json

dict1 = {'name': 'fengling', 'age': 18, 'sex': '男'}
json1 = json.dumps(dict1, ensure_ascii=False, indent=0)
print(json1)
print(type(json1))

执行结果:

{
"name": "fengling",
"age": 18,
"sex": "男"
}
<class 'str'>

你可能感兴趣的:(python中的各个模块的使用,python)