- 本文使用的 Python 版本为
3.12
。
反序列化
- 将
JSON字符串
解析为Python对象
叫做JSON的反序列化
,也叫做JSON的解码
。 - 反序列化一般使用
json
模块的loads
与load
方法。 loads
当中的s
并不是复数的意思,而是指处理的对象类型为str bytes 和 bytearray
。load
方法处理的对象类型为file like obj
。- 以上两个方法根据输入数据的不同,返回不同的
Python对象
。具体的转换关系见下表:
JSON 字符串 | Python 对象 |
---|---|
object | dict |
array | list |
string | str |
number(integer) | int |
number(real) | float |
false | False |
true | True |
null | None |
JSON 字符串的反序列化
str bytes 和 bytearray
的反序列化,使用方法loads
。
# -\*- coding:utf-8 -\*-
import json
json_obj_str = '{"number": 88888888, "名字": "小明"}'
# encode 方法:将 字符串 转为 bytes
# decode 方法,将 bytes 转为 字符串
json_obj_bytes = json_obj_str.encode(encoding='UTF-8')
json_array_str = '[1, 2, 3, "hello"]'
json_str = '"hello"'
json_int_num_str = '6666'
json_float_num_str = '888.888'
json_true_str = 'true'
json_false_str = 'false'
json_none_str = 'null'
def json\_str\_decode(arg):
python_obj = json.loads(arg)
print(f'value: {python\_obj}, type: {type(python\_obj)}')
for tmp in [json_obj_str, json_obj_bytes, json_array_str, json_str, json_int_num_str, json_float_num_str,
json_true_str, json_false_str, json_none_str]:
json_str_decode(tmp)
'''
输出为:
value: {'number': 88888888, '名字': '小明'}, type: <class 'dict'>
value: {'number': 88888888, '名字': '小明'}, type: <class 'dict'>
value: [1, 2, 3, 'hello'], type: <class 'list'>
value: hello, type: <class 'str'>
value: 6666, type: <class 'int'>
value: 888.888, type: <class 'float'>
value: True, type: <class 'bool'>
value: False, type: <class 'bool'>
value: None, type: <class 'NoneType'>
'''
JSON 文件的反序列化
- 文件的反序列化,使用方法
load
。
# -\*- coding:utf-8 -\*-
import json
'''
test.json 文件内容如下:
{
"名字": "小明",
"number": 888888,
"女朋友": null
}
'''
# 当 json 文件中含有中文时,得指定编码为 UTF-8
with open('test.json', 'r', encoding='UTF-8') as f:
python_obj = json.load(f)
print(f'value: {python\_obj}, type: {type(python\_obj)}')
'''
输出为:
value: {'名字': '小明', 'number': 888888, '女朋友': None}, type: <class 'dict'>
'''
序列化
- 将
Python对象
转为JSON字符串
叫做JSON的序列化
,也叫做JSON的编码
。 - 序列化一般使用
json
模块的dumps
与dump
方法。 dumps
当中的s
并不是复数的意思,而是指字符串,即将Python对象
编码为字符串
。dump
方法将Python对象
编码为字符串
并写入file like obj
中。
Python 对象的序列化
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!