Serialization of Json&pickle

Source: Internet
Author: User

First, brief

The data we write in the file is only a string, but what if we want to save the memory data object to the hard disk? Here's to say serialization: JSON & Pickle

Second, JSON serialization

1. Serialization of dumps and loads deserialization

Serialization of Dumps ()

ImportJson#Importing JSON modulesInfo= {    'name':"Seven",    " Age": 32} with open ("Test.txt","W") as F:#write in normal modedata = Json.dumps (info)#Convert a memory object to a stringF.write (data)#Write to File #content in the Text.txt file{"name":"Seven"," Age": 32}

Loads () deserialization

Import JSON with open ("test.txt","R") as F:  # Read in normal mode    data = Json.loads (F.read ())   # uses loads to deserialize print(The Data.get ("Age  "# output 32

2. Dump serialization and load deserialization

Dump () serialization

ImportJSON Info= {    'name':"Seven",    " Age": 32} with open ("Test.txt","W") as F:#the file opens in a written wayJson.dump (INFO,F)#The 1th parameter is the memory data object, and the 2nd parameter is the file handle #content in the Text.txt file{"name":"Seven"," Age": 32}

Load () deserialization

Import JSON with open ("test.txt","R") as F:   #  Open the file as read    data = Json.load (f)  # input File object print(data[ "  Age "  # output 32

3. Serialization functions

ImportJSONdefSayhi (name):#function    Print("Name:", name) info= {    'name':"Seven",    " Age": 32,    "func": Sayhi#reference Sayhi function name} with open ("Test.txt","W") as F:json.dump (info,f)#serializing an Info data object #OutputFile"D:\Python\Python35\lib\json\encoder.py", Line 403,inch_iterencode_dictyield  fromchunks File"D:\Python\Python35\lib\json\encoder.py", line 436,inch_iterencode o=_default (o) File"D:\Python\Python35\lib\json\encoder.py", line 179,inchdefaultRaiseTypeError (repr (o) +"is not JSON serializable") TypeError:<function Sayhi at 0x00000000006dd510> is  notJSON serializable#JSON serialization not supported

Summary:

    1. Dumps and loads are used in pairs, and dump and load are used in pairs.
    2. Dumps and loads because the serialized is the content, so the following to add S, but dump and load serialized content is the object, so singular.
    3. JSON can only handle simple data types, such as dictionaries, lists, strings, etc., and cannot handle complex data types such as functions.
    4. JSON is common in all languages, JSON is supported in all languages, and if we need python to interact with other languages, it is in JSON format.
Ii. Serialization of Pickle

1. Serialization of dumps and loads deserialization

Serialization of Dumps ()

ImportPickle Info= {    'name':"Seven",    " Age": 32,} with open ("Test.txt","WB") as F:#write in binary formdata = Pickle.dumps (info)#serializing into a stringF.write (data)#writing to the Test.txt file #output to content in a Test.txt file?} Q (X ageqkx nameqx sevenqu.

Loads () deserialization

Import Pickle with open ("test.txt","RB"#  Read in binary mode    data = Pickle.loads (F.read ())   # Deserialize the operation print(Data.get ( "  Age "  # output 32

2. Dump serialization and load deserialization

Dump () serialization

ImportPickle Info= {    'name':"Seven",    " Age": 32,} with open ("Test.txt","WB") as F:pickle.dump (info,f)#Serialization of #Output?} Q (X ageqkx nameqx sevenqu.

Load () deserialization

Import Pickle with open ("test.txt","RB") as F:     = Pickle.load (f)  # is deserialized into memory object print(Data.get (" Age "# output 32

From the above results, there seems to be no difference between JSON and pickle. But don't forget, we say JSON can only serialize simple data types, and pickle can serialize all the data types in Python, including functions, classes, and so on, let's look at how to serialize the function. What's more, pickle serializes bytes, and JSON serializes characters, this should be noted.

3. Serialization functions

Serialization of ①

ImportPickledefSayhi (name):#function    Print("Hello:", name) info= {    'name':"Seven",    " Age": 32,    "func": Sayhi#The value of "func" corresponds to Sayhi, which is the name of the function} with open ("Test.txt","WB") as F:data=Pickle.dumps (Info) f.write (data)#output Test.txt?} Q (X funcqc__main__sayhiqx ageqkx nameqx seven.

② deserialization

ImportPickledefSayhi (name):#This function must be written in deserialization, otherwise it will be an error because the function is not loaded into memory at the time of loading    Print("Hello:", name) with open ("Test.txt","RB") as F:data=pickle.loads (F.read ())Print(Data.get (" Age")) Data.get ("func")("Seven")#Execute function Sayhi #Output32Hello:seven#The logic in the output function body is also variable, and I'm not going to do a demo here.

Summary:

    1. JSON values support simple data types, and pickle supports all data types.
    2. Pickle can only support serialization and deserialization of Python itself and cannot be used as a data interaction with other languages, and JSON can.
    3. Pickle serializes the entire data object, so when deserializing the function, the logic in the function body changes and goes with the new function body.
    4. Pickle and JSON in 3.0 can only dump once and load once, in 2.7 can dump several times, load several times, anyway, only remember, only need to dump once, load once.

Serialization of Json&pickle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.