JSON & Pickle Modules
JSON modules: Only for simple data types, is a cross-platform module.
Let's say we have a piece of data that defines this:
= { ‘name‘:‘alex‘, ‘age‘:22}
For this simple data type, we can directly use theJson
For serialization and deserialization of data:
Serialization dumps
:
import=open("test.text","wb")f.write(json.dumps(info))f.close()
Similarly, we can use dump
methods instead of dumps
methods:
You only need tof.write(json.dumps(info))
Replace json.dump(info,f)
it with.
Deserialization loads
:
import=open("test.txt","rb"= json.loads(f.read())
Similarly, we can use load
methods instead of loads
methods:
You only need tof.write(json.dumps(info))
Replace json.dump(info,f)
it with.
Pickle module: Capable of converting complex data types, is a unique data type of Python.
Through the JSON module above we find that JSON can only pass some simple data types, if we want to info
add a function?
def sayhi(name): print("hello2,"= {‘name‘:‘alex‘,‘age‘:22‘func‘:sayhi }
This time, we need to use our pickle module.
Serialization dumps
:
import=open("test.text","wb")f.write(json.pickle(info))f.close()
Similarly, we can use dump
methods instead of dumps
methods:
You only need tof.write(pickle.dumps(info))
Replace pickle.dump(info,f)
it with.
Deserialization loads
:
import pickledef sayhi(name): print("hi"+=open("test.txt","rb"= pickle.loads(f.read())
Similarly, we can use load
methods instead of loads
methods:
You only need tof.write(picklejson.dumps(info))
Replace pickle.dump(info,f)
it with.
It is important to note that the function needs to be redefined when deserializing the session sayhi()
.
Precautions:
When serializing and deserializing data using the JSON module and the Pickle module, it is a dump-to- load principle , which is to dump only one copy and load only one copy.
Json&pickle Module of Python basics