一、json模块
能在网络上传递的只有字节,而转成字节的只有字符串
1、dic(字典)--->通过json.dumps(dic)--->转换成json格式的str --->通过encode-->转换成字节-->在网络上传递
# 字典通过json转成str,然后转换成字节 import json dic = {'username':'admin','passwd':'admin'} print(dic,type(dic)) #{'username': 'admin', 'passwd': 'admin'} <class 'dict'> ret = json.dumps(dic) print(ret,type(ret)) #{"username": "admin", "passwd": "admin"} <class 'str'> uncode_1 = ret.encode('UTF-8') print(uncode_1,type(uncode_1)) #b'{"username": "admin", "passwd": "admin"}' <class 'bytes'>
2、字节转字符串:decode
# 字节转字符串 str = uncode_1.decode('utf-8') print(str,type(str)) #{"username": "admin", "passwd": "admin"} <class 'str'>
3、字符串转换成字典:json.loads
# 字符串转换成字典 dct = json.loads(str) print(dct,type(dct)) #{'username': 'admin', 'passwd': 'admin'} <class 'dict'>
# 把字典内的数据写到文件内
# 把字典内的数据写到文件内 context = {'北京':{'朝阳':{'望京':'SOHO'},'海淀':{'中关村':'海伦大厦'}}} str_con = json.dumps(context,ensure_ascii=False) #ensure_ascii=False 不按照ascii来转,确保中文直接可以写进去 with open('city',mode='w',encoding='utf-8') as f: f.write(str_con) f.close() # 读取文件内的数据,并且把读取出来的数据转成字典 with open('city',mode='r',encoding='utf-8') as f: str=f.read() dic = json.loads(str)