码迷,mamicode.com
首页 > 编程语言 > 详细

Python的json and pickle序列化

时间:2017-08-13 20:53:16      阅读:9      评论:0      收藏:0      [点我收藏+]

标签:author   反序   write   and   bsp   logs   ret   load   pickle   

json序列化和json反序列化

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 人生入戏
import json

a = {
    "name":"test",
    "age":"20",
}
#json序列化
with open("json_test","w",encoding="utf-8") as f:
    f.write(json.dumps(a)) # 等同于这个 json.dump(a,f)

#json反序列化
with open("json_test","r",encoding="utf-8") as f:
    print(json.loads(f.read())) #等同于这个  print(json.load(f))

pickle序列化和反序列化

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 人生入戏
import pickle

def hello():
    print("Hello!")
    return 0
a = {
    "name":"test",
    "age":"20",
    "func":hello
}
with open("json_test","wb") as f:
    f.write(pickle.dumps(a))  #等同于这个 pickle.dump(a,f)

with open("json_test","rb") as f:
    print(pickle.loads(f.read())["func"]()) #等同于这个 print(pickle.load(f)["func"]())

 

Python的json and pickle序列化

标签:author   反序   write   and   bsp   logs   ret   load   pickle   

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!