Json & Pickle Data serialization

Source: Internet
Author: User
Tags serialization

Premise:

Text files can only be written in string or ASCII format content.

info={'name':'Zoe','age': 18 }f=open ('test.txt','w') f.write (info)   # write the contents of the dictionary format in the text file, and the execution will error. f.closed ()

The workaround is to change f.write (info) to F.write (str (info)).

But this is relatively low-end.

At the same time, the file is read into the environment through open () and is read in a string format. The above operation is serialized and deserialized after the operation of the read file.

F=open ('test.txt','r') data=f.read () Print (Type (data))   # return class ' str ' # To preserve the original format of the data, you also need to convert the data. data_new=eval (data)print(type (data_new))print(data_new)

Return:

However, the above methods of serialization and deserialization are not general usages. Only when we don't understand the json,pickle of the serialization module. Next we introduce the two modules for serialization.

Two modules for serialization

    • JSON, used to convert between string and Python data types
    • Pickle for conversion between Python-specific types and Python data types

The JSON module provides four functions: dumps, dump, loads, load

The Pickle module provides four functions: dumps, dump, loads, load

Json

Example 1:

 import   jsoninfo  ={"  name   ' : "  zoe   ",  " age  " : 18}f  =open ( "  Test.txt   ", "   W   " ) F.write (Json.dumps (info)) #序列化. Converts info to a string, written to a text file F.close ()  
Import jsonf=open ('test.txt','r') data=  Json.loads (F.read ())   #反序列化. Use the loads method to print the string (data (type)) F.close ()

Example 2:

>>>ImportJSON>>>defSayhi (name):Print('Hello,', name)>>> info={'name':'Zoe',' Age': 18,'func': Sayhi}>>> F=open ('Test.txt','W')>>>F.write (Json.dumps (info)) #函数sayhi的内存地址不是json可以序列化的参数. Traceback (most recent): File"<pyshell#12>", Line 1,inch<module>F.write (Json.dumps (info)) File"C:\Users\Zoe\Anaconda3\lib\json\__init__.py", line 230,inchdumpsreturn_default_encoder.encode (obj) File"C:\Users\Zoe\Anaconda3\lib\json\encoder.py", line 198,inchencode chunks= Self.iterencode (o, _one_shot=True) File"C:\Users\Zoe\Anaconda3\lib\json\encoder.py", line 256,inchIterencodereturn_iterencode (o, 0) File"C:\Users\Zoe\Anaconda3\lib\json\encoder.py", line 179,inchdefaultRaiseTypeError (repr (o) +"is not JSON serializable") TypeError:<function Sayhi at 0x000000000317f8c8> is  notJSON serializable

Therefore, JSON can only support simple data types such as dictionaries, lists, strings, and so on. ——

JSON is primarily used for data interaction between different languages. For example, the interaction of dictionaries between Java and Python, classes, functions and other complex JSON can not be processed and interacted between different languages.

XML is a kind of markup language, which is gradually replaced by JSON, which is mainly in the data interaction between different languages and programs. Because JSON is more concise and clearer. JSON is currently the mainstream module for data interaction between different languages.

JSON can only handle simple, while pickle is used to handle complex data types.

JSON and Pickle operate exactly the same as JSON.

Pickle

Example 1:

ImportPickledefSayhi (name):Print('Hello,', name) info={'name':'Zoe',' Age': 18,'func': Sayhi}f=open ('Test.txt','WB')#write a file in binary modeF.write (Pickle.dumps (info)) #pickle. Dump (info,f) is fully equivalent f.close ()

Deserialization:

ImportPickledefSayhi (name):Print('Hello World', name) F=open ('Test.txt','RB') A=pickle.loads (F.read ()) #完全等价于pickle. Load (f)Print(a) a['func']('Zoe')   " "if the Sayhi () function is not in the program in the deserialization, an error occurs. However, a sayhi () function with the same name defined in the program can be read and invoked. The memory addresses between the two programs are not accessible to each other, so in function serialization, pickle can only be used in Python. " "

Small knowledge:

JSON and Pickle are dumps two times during the file write process and are written two times;

JSON and pickle are loads in a file and can only be loads once in 3.x.

The first dump in 2.x can be loads for the first time. But this is not good.

So for the same file write and read remember to dump only once, load once. If you want to dump each one at a time, dump it into a different file.

Json & Pickle Data serialization

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.