python数据类型 -> json对象
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys
sys.path.append('.')
import json
# python字典对象
contant = {
'name': 'tester',
'sex':'男',
'age': 18,
'is_bool': True
}
def serialization(*args, **kwargs):
"""
序列化
"""
return json.dumps(*args, **kwargs)
if __name__ == "__main__":
print(serialization(contant))
执行结果:
{"name": "tester", "sex": "\u7537", "age": 18, "is_bool": true}
可以看到成功,序列化里面有以下特点:
True
转换为ture
我们能让中文正常显示吗?当然可以,只需要在序列化时设置一个参数。
if __name__ == "__main__":
print(serialization(contant,ensure_ascii=False))
运行结果:
{"name": "tester", "sex": "男", "age": 18, "is_bool": true}
可以看到中文已经正常显示了。
json对象 -> python数据类型
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys
sys.path.append('.')
import json
contant = {
'name': 'tester',
'sex': '男',
'age': 18,
'is_bool': True
}
def serialization(*args, **kwargs):
"""
序列化
"""
return json.dumps(*args, **kwargs)
def deserialization(*args, **kwargs):
"""
反序列化
"""
return json.loads(*args, **kwargs)
if __name__ == "__main__":
res = serialization(contant, ensure_ascii=False)
print(deserialization(res))
执行结果:
{'name': 'tester', 'sex': '男', 'age': 18, 'is_bool': True}
可以看到反序列化之后结果都显示回了contant变量定义的python字典对象
那我们能不能直接反序列化contant字典呢?我们来试一下
if __name__ == "__main__":
print(deserialization(contant))
运行结果:
File "D:\Python3\lib\json\__init__.py", line 341, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not dict
可以看到报错了,大致意思为:json对象应该时一个字符串,字节或字节数组;不是一个字典。
所以我们在反序列化的时候传的值必须时json对象
格式。
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
本文地址:https://blog.csdn.net/oHuaXin1234/article/details/107239948
如对本文有疑问, 点击进行留言回复!!
自我记录:Python学习之OpenCV 05 图片的颜色提取
python初体验:cmd输入python但是打开microsoft store问题
接口测试框架实战(一) | Requests 与接口请求构造
网友评论