python基础-序列化问题json和pickle

json的序列化和反序列化

# json格式
# 为什么要序列化:数据传输对数据的封装,类似于加密解密



import json
d={'山东':['济南','青岛'],'广东':["佛山","潮汕"]}
s={"ada":"ali"}
# 序列化,内涵参数为相应格式,将相应格式转换为json字符串
ret1=json.dumps(d)
ret2=json.dumps(s)
print(ret1)
print(ret2)
# {"\u5c71\u4e1c": ["\u6d4e\u5357", "\u9752\u5c9b"], "\u5e7f\u4e1c": ["\u4f5b\u5c71", "\u6f6e\u6c55"]}
# {"ada": "ali"}

# 序列化,内涵参数为相应格式,将相应格式转换为json字符串,写入文件
f=open("dump.txt","w")
json.dump(d,f)
f.close()
# 将d这个字典搞进dump.txt这个文件,显示以下内容
# {"\u5c71\u4e1c": ["\u6d4e\u5357", "\u9752\u5c9b"], "\u5e7f\u4e1c": ["\u4f5b\u5c71", "\u6f6e\u6c55"]}

#反序列化,内涵参数必须为json字符串,将json字符串转换为相应格式
load1=json.loads(ret1);load2=json.loads(ret2)
print(load1)
print(load2)
# {'山东': ['济南', '青岛'], '广东': ['佛山', '潮汕']}
# {'ada': 'ali'}


# 一般数据直接读就行,json包涵的数据类型适合json读取,主要用于状态存档
f=open("hello.log")
data = f.read()

data = json.dumps(data)
print(data)
# "Thu, 27 Apr 2017 10:00:24 root [line:10] DEBUG debug\n" \
# "Thu, 27 Apr 2017 10:00:24 root [line:11] INFO info\n" \
# "Thu, 27 Apr 2017 10:00:24 root [line:12] WARNING warning\n" \
# "Thu, 27 Apr 2017 10:00:24 root [line:13] ERROR error\n" \
# "Thu, 27 Apr 2017 10:00:24 root [line:14] CRITICAL critical\n"

rett = json.loads(data)
print(rett)
# Thu, 27 Apr 2017 10:00:24 root [line:10] DEBUG debug
# Thu, 27 Apr 2017 10:00:24 root [line:11] INFO info
# Thu, 27 Apr 2017 10:00:24 root [line:12] WARNING warning
# Thu, 27 Apr 2017 10:00:24 root [line:13] ERROR error
# Thu, 27 Apr 2017 10:00:24 root [line:14] CRITICAL critical

  

关于pickle的存取和读取

import pickle
#pickle 是字节数据

d = {'name':'ada','age':24}
# d1 = pickle.dump(d)

with open("pickle.txt","wb") as fw:
    pickle.dump(d,fw)


with open("pickle.txt","rb") as fr:
    pickle.load(fr)

# 一个字典a = {'name':'Tom','age':22}
# 写入时,用pickle.dump存到本地文件,所存数据的结构就是字典,而普通的file.write写入文件的是字符串。
# 读取时,pickle.load返回的是一个字典,file.read返回的是一个字符串。

  

 

posted @ 2017-09-20 15:35  Adamanter  阅读(124)  评论(0编辑  收藏  举报