Python-191. JSON and Pickle module what is serialization and deserialization
- Serialization: is to convert the in-memory data structure into an intermediate format, save the converted intermediate format to the hard disk, or network-based transmission
- Deserialization: An intermediate format that is transferred from a hard disk or a network into an in-memory data structure
2. What is the use of serialization and deserialization
- Saves the state of a program by storing it in an intermediate format to the hard disk
- Data can interact across platforms, and different programming languages can interact with each other by serializing them into an intermediate format
- The text file saved to the hard disk is a string, and when used again, the data in the hard drive needs to be converted to the previous data type state
3. The difference between JSON and pickle modules ①
json
- Pros:
jison
cross-platform, all programming languages can be converted into json
formats
- Cons: Only supported
python
partial data types
Ii
pickle
- Pros:
python
All the data supported is rational
- Cons:
pickle
can only be recognized python
, not cross-platform
Correspondence between ③json type and Python type
4. Serialization of JSON ①
json.dumps(内存的数据)
- Description: Single quotation marks are
json
not recognized, only double quotes are used, and json
single quotes are converted to double quotes during serialization.
# 导入json模块import json# 内存中数据dic={‘name‘:‘xut‘,‘age‘:18,‘sex‘:‘male‘}# json序列化:内存中的数据类型---->json中间格式json_str=json.dumps(dic)# print(json_str,type(json_str))# 将序列化中间格式写到文件with open(r‘db.json‘,‘wt‘,encoding=‘utf-8‘) as f: f.write(json_str)
Ii
json.dump(内存中数据对象,文件))
json.dump
You can merge the two steps above
import jsondic={‘name‘:‘xut‘,‘age‘:18,‘sex‘:‘male‘}with open(r‘db.json‘,‘wt‘,encoding=‘utf-8‘) as f: json.dump(dic,f)
③ Summary
- Serialize different data types and write to different files
5. Deserialization of JSON ①
json.loads(文件中的中间格式)
JSON and Pickle modules