json与pickle-序列化

python中,json和pickle都是可以序列化的方式,但是不同的是,json是公用的,即所有语言都可以使用,但是pickle仅仅在python内部才能使用。

两者拥有相同的方法,作用也是相同的,但是json只能序列化像字符串字典列表等这些简单的数据类型,因为python里有的,其他语言里不一定有,所以,只有大部分的语言都有的,并且类型相同的数据类型,json才会有。

  • Json 模块提供了四个功能:dumps、dump、loads、load
  • pickle 模块提供了四个功能:dumps、dump、loads、load

json的序列化与反序列化

import json
info = {
    "name":"DuZhaoqi","age":23} 
f = open("infomation.txt","w",encoding="utf-8")
f.write(json.dumps(info)) #序列化
import json

f = open("infomation.txt","r",encoding="utf-8")
data = json.loads(f.read()) #反序列化
print(data)
print(data["age"])

pickle的序列化与反序列化
因为pickle的读写都是用的为二进制,所以,我们需要使用 wbrb

import pickle

def sayhi(name):
    print("Hello,",name)

info = {
    "name":"DuZhaoqi", "age":23,"func":sayhi}

f = open("infomation.txt","wb")
f.write(pickle.dumps(info)) #序列化

f.close()
import pickle

def sayhi(name):
    print("Hello,",name)
    print("hello".upper(),name)

info = {
    "name":"DuZhaoqi","age":23}

f = open("infomation.txt","rb")
data = pickle.loads(f.read()) #反序列化

print(data)
print(data["age"])
print(data["func"]("Tom"))

除了dumpsloads,还可以使用dumpload,我用pickle来演示,效果都是一样的

import pickle

def sayhi(name):
    print("Hello,",name)

info = {
    "name":"DuZhaoqi", "age":23,"func":sayhi}

f = open("infomation.txt","wb")

pickle.dump(info,f) #f.write(pickle.dumps(info))

f.close()
import pickle

def sayhi(name):
    print("Hello,",name)
    print("hello".upper(),name)

info = {
    "name":"DuZhaoqi","age":23}

f = open("infomation.txt","rb")

data = pickle.load(f)  #data = pickle.loads(f.read()) #反序列化

print(data)
print(data["age"])
print(data["func"]("Tom"))

注意:在python2中,json可以多次dumploads,但是在python3中,json可以多次dumps,但是不能多次loads了,这一点需要注意。

你可能感兴趣的:(python模块,jsonamppickle,python)