序列化
将程序内对象转化为二进制数据——序列化Serialize
将二进制数据转化为程序内对象——反序列化Deserialize
在文件系统保存或者传输到网络上,我们都需要将其转化为二进制数据。
JSON数据格式
我们可以用python将数据转化为一个json格式的二进制数据从windows传输到linux上,然后用c++读取linux上的数据,举这个例子是为了说明json可以跨语言跨系统。
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import json
# In[2]:
d = {
"symbol":"BTCUSDT",
"exhcange":"OKEX",
"interval":"1m",
"close":3800
}
# In[4]:
print(type(d),d)
# In[5]:
# 序列化
# dump的意思是将内存中的对象加载为二进制数据,s是string的意思,就是说转化后的数据是一个str
data_str = json.dumps(d)
print(type(data_str),data_str)
# In[8]:
# 写入文件
with open("json_demo.txt","w") as f:
f.write(data_str)
# In[9]:
# {"symbol": "BTCUSDT", "exhcange": "OKEX", "interval": "1m", "close": 3800}
# In[10]:
# 读取文件,反序列化
with open("json_demo.txt","r") as f:
line = f.read()
print(line)
data = json.loads(line)
print(type(data),data)
# In[11]:
# 复杂结构
temp = {
"str":"hello",
"int":1,
"float":0.5,
"bool":True,
"dict":{
"demo":"test"
},
"list":[1,2,3]
}
with open("json_demo2.txt","w") as f:
json.dump(temp,f,indent=4)
# indent 写进数据的缩进
# In[12]:
# {
# "str": "hello",
# "int": 1,
# "float": 0.5,
# "bool": true,
# "dict": {
# "demo": "test"
# },
# "list": [
# 1,
# 2,
# 3
# ]
# }
# In[16]:
with open("json_demo2.txt","r") as f:
res = json.load(f)
print(type(res),res)
# <class 'dict'> {'str': 'hello', 'int': 1, 'float': 0.5, 'bool': True, 'dict': {'demo': 'test'}, 'list': [1, 2, 3]}