Json&pickle Module

Source: Internet
Author: User
Tags serialization

Before we learned to use the eval built-in method to turn a string into a Python object, however, the Eval method is limited and can be used for normal data types, json.loads and eval, but when it comes to special types, eval doesn't work. So the focus of eval is usually to execute a string expression and return the value of the expression

1 Import JSON 2 x="[null,true,false,1]"3  Print (eval (x)) #报错, cannot resolve null type, And JSON will be 4 .

What is serialization?

The process of changing an object (variable) from memory to a storage or transfer is called serialization, and in Python it is called pickling, which is also called serialization,marshalling,flattening in other languages, and so on.

Why serialize?

1: Persistent Save state

It is necessary to know that the execution of a software/program is dealing with a series of state changes, in which the ' state ' is stored in memory in the form of a variety of structured data types (which can also be simply understood as variables).

Memory is unable to permanently save the data, when the program has been running for some time, we power down or restart the program, in memory of the program in the previous period of time data (structure) was emptied.

Save all the data in the program's current memory (to a file) before powering down or restarting the program, so that the next time the program executes the data before it can be loaded from the file, it will continue to execute, which is serialization.

Specifically, you play the call of duty rushed to the 13th level, you save the game state, shut down the machine to leave, the next time to play, but also from the last position began to continue the level. Or, for example, the suspend of the virtual machine state, and so on.

2: Cross-platform data interaction

After serialization, not only can the serialized content be written to disk, but also can be transmitted over the network to other machines, if the sending and receiving parties agreed to use a serialized format, then break the platform/language differences brought about by the limitations, to achieve cross-platform data interaction.

In turn, re-reading the variable contents from the serialized object into memory is called deserialization, i.e. unpickling.

How to serialize JSON and pickle:

Json

If we are going to pass objects between different programming languages, we have to serialize the object into a standard format, such as XML, but the better way is to serialize it to JSON, because JSON represents a string that can be read by all languages, easily stored to disk, or transmitted over a network. JSON is not only a standard format, but also faster than XML, and can be read directly in the Web page, very convenient.

JSON represents objects that are standard JavaScript language objects, and JSON and Python have built-in data types that correspond to the following:

Import JSON dic={'name':'Alvin',' Age': at,'Sex':'male'}print (Type (DIC)) #<class 'Dict'>J=json.dumps (DIC) print (Type (j)) #<class 'Str'>F=open ('Serializing Objects','W') F.write (j) #-------------------equivalent to Json.dump (dic,f) f.close () #-----------------------------deserialization <br>Import jsonf=open ('Serializing Objects') Data=json.loads (F.read ()) # equivalent to Data=json.load (f)
import JSON#DCT="{' 1 ': 111}"#json not recognized single quotes #dct=str ({"1  ":111}) #报错 because the generated data is still single quotes: {'one'1}DCT ='{' 1 ': ' 111 '}'print (Json.loads (DCT)) #conclusion: #        No matter how the data is created, As long as the JSON format is satisfied, it can be json.loads out, not necessarily dumps data to loads

Pickle

Import Pickle dic={'name':'Alvin',' Age': at,'Sex':'male'} print (Type (DIC)) #<class 'Dict'>J=pickle.dumps (DIC) print (Type (j)) #<class 'bytes'>F=open ('Serialized Object _pickle','WB') #注意是w是写入str, WB is written bytes,j is'bytes'F.write (j) #-------------------equivalent to Pickle.dump (dic,f) f.close () #-------------------------deserialization Import Picklef=open ('Serialized Object _pickle','RB') Data=pickle.loads (F.read ()) # equivalent to Data=pickle.load (f) Print (data[' Age'])

The problem with Pickle is the same as for all other programming language-specific serialization problems, that is, it can only be used in Python, and may be incompatible with each other in Python, so it's okay to save only those unimportant data with pickle and not successfully deserialize it.

Json&pickle Module

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.