序列化模块

序列化模块

jason格式数据:跨语言传输

d = {'username': 'jason', 'pwd': 123}
import json

1.将python其他数据转换成json格式字符串(序列化)
'''序列化'''
res = json.dumps(d)
print(res,type(res))
# {"username": "jason", "pwd": 123}<class 'str'> 双引号,json唯一标识

2.将json格式字符串转成当前语言对应的某个数据类型
'''反序列化'''
d = {'username': 'jason', 'pwd': 123}
res1 = json.loads(res)
print(res1,type(res1))
# {'username': 'jason', 'pwd': 123} <class 'dict'>

序列化模块(2)
import json


bytes_data = b'{"username": "jason", "pwd": 123}'
bytes_str = bytes_data.decode('utf8')
print(bytes_str) # {"username": "jason", "pwd": 123}
print(type(bytes_str)) # <class 'str'>
bytes_dict = json.loads(bytes_str) 
print(bytes_dict) # {'username': 'jason', 'pwd': 123}
print(type(bytes_dict)) # <class 'dict'>

序列化模块(3)
'''
暂且可以简单的理解为:
	序列化就是将其他数据类型转化成字符串过程
		json.dumps()
	反序列化就是将字符串转化成其他类型数据类型
		json.loads()
'''

序列化模块(4)

# 将字典写入文件再取出
d = {'username': 'jason', 'pwd': 123}

with open(r'a.txt', 'w', encoding='utf8') as f:
    f.write(str(d))
    
with open(r'a.txt', 'r', encoding='utf8') as f1:
    data = f1.read()
    data1 = dict(data)
print(data1,type(data1))
# 报错  									达咩达咩

序列化模块(4.1)
import json

d = {'username': 'jason', 'pwd': 123}
with open(r'a.txt', 'w', encoding='utf8') as f:
    res = json.dumps(d)
    f.write(res)
# 序列化成json格式字符串

with open(r'a.txt', 'r', encoding='utf8') as f:
    res = f.read()
res1 = json.loads(res)
print(type(res1))
# <class 'dict'>
'''json.dumps()和json.loads()直接操控数据'''

序列化模块(4.2)
import json

d1 = {'username': 'tom', 'password': 123, 'hobby': [11, 22, 33]}
with open(r'a.txt', 'w', encoding='utf8') as f:
    json.dump(d1, f)
with open(r'a.txt', 'r', encoding='utf8') as f:
    res = json.load(f)
print(res, type(res))
# {'username': 'tom', 'password': 123, 'hobby': [11, 22, 33]} <class 'dict'>

'''json.dump()和json.load()结合文件一起操作''’

序列化模块(4.3)
d1 = {'username': 'tony好帅哦 我好喜欢', 'pwd': 123,'hobby':[11,22,33]}
print(json.dumps(d1,ensure_ascii=False))

# 若文本中出现中文需要做转换

溜了溜了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值