标签:写入文件 coding http 字典 odi utf-8 mda 反序列化 mode
data_json = ‘{"msg": "登录成功", "code": "10001", "data": null, "status":1}‘ data_dict = json.loads(data_json, encoding="utf-8")
这个时候,如果使用 eval(data_json) 将会报错。
NameError: name ‘null‘ is not defined
data_json = ‘{"msg": "登录成功", "code": "10001", "data": null, "status":1}‘ with open("json_file.txt", mode="r", encoding="utf-8") as file: date_dict = json.load(file)
将Python中特定类型进行字符串化操作,即转换为json格式的数据
注意:字典、列表等都可以进行字符串话操作,变为json格式
one_dict = {"name": "菲菲", "age": 18, "money": None} one_str = str(one_dict) one_json = json.dumps(one_dict) two_json = json.dumps(one_dict, ensure_ascii=False)
one_tuple = ["菲菲", 18, None] one_str = str(one_tuple) one_json = json.dumps(one_tuple) two_json = json.dumps(one_tuple, ensure_ascii=False)
one_dict = {"name": "字典型", "age": 18, "money": None} with open("json_file.txt", mode="a",encoding="utf-8") as file: json.dump(one_dict, file, ensure_ascii=False)
one_tuple = ["菲菲", 18, None] with open("json_file.txt", mode="a", encoding="utf-8") as file: json.dump(one_tuple, file, ensure_ascii=False)
loads 将json格式的数据转化为dict
dumps 将字典、列表t等类型的数据转化成json格式
load 读取json格式文件,并返回dict
dump 将字典、列表等格式的数据转化为json格式,写入文件中
试了一下,
load,loads好像是只能转化成为dict。(反序列化,流——对象)
dump,dumps可以将列表,字典数据转化为json格式。(序列化,对象——可保存或可传输格式)
单词后面有s,都是对文件操作。
Python json库中load、loads、dump、dumps的区别与用法
标签:写入文件 coding http 字典 odi utf-8 mda 反序列化 mode
原文地址:https://www.cnblogs.com/jszfy/p/11306395.html