🍔经过文件将字典转成字符串存入(序列化) dic = {'name':'egon','age':18} with open('db.txt','w',encoding='utf-8')as f : f.write(str(dic)) 🍔经过"eval"函数将拿出来的字符串转成数据结构(反序列化) with open('db.txt','r',encoding='utf-8')as f: data = f.read() dic = eval(data) print(dic) # {'name': 'egon', 'age': 18} print(type(dic)) # <class 'dict'>
x="[null,true,false,1]" print(eval(x)) # 报错,没法解析null类型
把某个语言的变量转成 json 格式字符串html
内存中的数据结构----->转成一种中间格式(字符串)----->存到文件中前端
把 json 格式字符串转成某个语言的变量java
文件----->读取中间格式(字符串)----->eval( ) 转成内存中数据结构python
序列化两种用途:编程
存取数据 (格式标准), 一个程序写入, 另外一个程序读取 (这两个程序能够是使用不一样的语言写的)
例如 : 后端给前端的数据就是 "json" 格式字符串
json 模块能够序列化:字典,列表,布尔json
json 数据类型和 python 数据类型对应关系表后端
Json类型 | Python类型 |
---|---|
{} | dict |
[] | list |
"string" | str |
1.73 | int或float |
true/false | True/False |
null | None |
dic = {'movieIds': [111, 222, 333, 444],\ 'stids': [{'movieId': 11, 'stid': 1}, \ {'movieId': 22, 'stid': 2}, \ {'movieId': 33, 'stid': 3}]} res = json.dumps(dic) print(res) '''能够发现对应格式已经发生了转变 {"movieIds": [111, 222, 333, 444],\ "stids": [{"movieId": 11, "stid": 1},{"movieId": 22, "stid": 2}, {"movieId": 33, "stid": 3}]} '''
import json dic = {"name":"song"} print(json.dumps(dic)) # {"name": "song"} s = '{"name": "song"}' print(json.loads(s)) # {'name': 'song'}
.dumps()
import json dic = {'name':'song','age':21} dic = json.dumps(dic) print(dic,type(dic)) # {"name": "song", "age": 21} <class 'str'> with open('db.json','a',encoding='utf-8')as f: f.write(dic)
.loads()
with open('db.json', 'rt', encoding='utf-8')as f: data = f.read() dic = json.loads(data) print(dic, type(dic)) # {'name': 'song', 'age': 21} <class 'dict'>
.dump()
import json dic = {'name':'song','age':21} with open('db1.json','wt',encoding='utf-8')as f: json.dump(dic,f)
.load()
with open('db1.json','rt',encoding='utf-8')as f: dic = json.load(f) print(dic,dic['age']) # {'name': 'song', 'age': 21} 21
import json dic = {"name": "派大星", "age": 22} res = json.dumps(dic) print(res) # {"name": "\u6d3e\u5927\u661f", "age": 22}
ensure_ascii=False
功能dic = {"name": "派大星", "age": 22} res = json.dumps(dic,ensure_ascii=False) print(res) # {"name": "派大星", "age": 22}
并无使用上的变化, 存的是什么, 取出来的仍是什么, 只不过人家内部帮你转成"uncode"格式保存
ps : java中,出于性能的考虑,有不少包来完成序列化和反序列化:谷歌的gson 阿里开源fastjson 等等网络