【python】json模块

序列化

将程序内对象转化为二进制数据——序列化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]}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m 宽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值