10.4JSON

JSON

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

json字符串→python数据结构

在python中,json字符串被转换成python特定的数据结构,如:

Json对象被转换为字典dist

import json
json_str='{"name":"qiyue","age":18}'
student=json.loads(json_str)
print(type(student))
print(student)

提示:因为json对象已被转换为dist,故我们需要的就是对dist的操作,如获取属性操作

print(student['age'])

json数组被转化为列表

import json
json_str='[{"name":"qiyue","age":18},{"name":"qiyue","age":18}]'
students=json.loads(json_str)
print(type(student))
print(student)

把json字符串向python数据类型转换的过程,专业名词为反序列化

python数据结构→json字符串

把python数据类型向json字符串转换的过程,专业名词为序列化

import json
student=[
    {'name':'qiyue','age':18,'flag':False},
    {'name':'qiyue','age':18}
]
json_str =json.dumps(student)
print(type(json_str))
print(json_str)

Last updated

Was this helpful?