Python Advanced -XII serialize (serialization), the serialization module

A, serialize serialized

1. What is the sequence of - converting the original dictionaries, lists and other content into a string of process is called serialization. 

For example, a data we calculated in python code requires the use of a program to another, then how do we give?
Now the way we can think of is that there is a file, and then another python program then read out from the file.
But we all know that is not the dictionary file for this concept, we can only put the data into the dictionary file.
You will be asked to convert a string into a dictionary is very simple str (dic) can be done, why we have to learn sequencing module it?
Yes serialization process is the process of becoming str (dic) from dic. Now you can str (dic), a dictionary named dic converted to a string,
but you have to how to convert a string into a dictionary it?
You must think of clever eval (), if we put a string type of dictionary str_dic passed to eval, you will get a return type of a dictionary.
eval () function is very powerful, but eval is doing what? e interpreted as official demo: string str as effective expression evaluated and returns the results.
BUT! Powerful functions come at a price. Security is its biggest drawback.
Imagine, if we are not a data structure read from the file, but rather a "Delete Files" similar destructive statement, then the consequences could scarcely conceive set.
The use of eval would bear the risk.
Therefore, we do not recommend to deserialize method manipulation eval (str converted into a data structure in python)


2, the sequence of the object
1), stored in some form of custom make objects persistent;
2), passing objects from one place to another.
3), make the program more maintainable.

Second, conventional sequencing module

1, json module 
json module provides four functions: dumps, the dump, loads, Load
  . 1) in memory serialization and deserialization (dumps loads)
. 1  Mport JSON
 2 DIC = { ' K1 ' : ' V1 ' , ' K2 ' : ' V2 ' , ' K3 ' : ' V3 ' }
 . 3  # str_dic = STR (DIC) # unsafe 
. 4 str_dic = json.dumps (DIC )   # serialization: converting a character string into a dictionary 
. 5  Print (type (str_dic), str_dic)   # <class 'STR'> { "K3": "V3", "K2": "V2", "K1" : "v1"} 
6  # Note that, json complete conversion character string as the type of dictionary is "" represented by 
. 7  
. 8= json.loads DIC1 (str_dic)   # deserialization: converts a string dictionary format into a dictionary 
. 9  Print (type (DIC1), DIC1)   # <class 'dict'> { 'K2': 'V2', 'K3': 'V3', 'K1': 'V1'} 
10  
. 11 dic_in_list = [. 1, [ ' A ' , ' B ' , ' C ' ],. 3, { ' K1 ' : ' V1 ' , ' K2 ' : ' V2 ' }]
 12 is str_dic_in_list = JSON.
dumps(dic_in_list)
13 print(type(str_dic_in_list), str_dic_in_list)  # <class 'str'> [1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]
14 dic_in_list1 = json.loads(str_dic_in_list)
15 print(type(dic_in_list1), dic_in_list1)  # <class 'list'> [1, ['a', 'b', 'c'], 3, {'k2': 'v2', 'k1': 'v1'}]
  2) file serialization and deserialization (dump load
. 1  # F = Open ( 'json_file', 'W') 
2  # DIC = { 'K1': 'V1', 'K2': 'V2', 'K3': 'V3'} 
. 3  # The json.dump (DIC , f) #dump method of receiving a file handle, which directly converts into a dictionary json string to the file 
. 4  # f.close () 
. 5  
. 6 F = Open ( ' json_file ' )
 . 7 DIC2 the json.load = (F)   # Load the method of receiving a file handle, which directly converts the file into a data structure returned json string 
. 8  f.close ()
 . 9  Print (type (DIC2), DIC2)   # <class 'dict'> { 'K2': 'V2' , 'k3': 'v3' , 'k1': 'v1'}
 3) ensure_ascii keyword arguments
. 1 F = Open ( ' File ' , ' W ' , encoding = ' UTF-. 8 ' )
 2 The json.dump ({ ' Nationality ' : ' Chinese ' }, F)
 . 3 RET = json.dumps ({ ' Nationality ' : ' Chinese ' })
 . 4 f.write (RET + ' \ n- ' )
 . 5 The json.dump ({ ' nationality ' : ' US ' }, F,ensure_ascii=False)
6= json.dumps RET ({ ' Nationality ' : ' US ' }, ensure_ascii = False)
 . 7 f.write (RET + ' \ n- ' )
 . 8 f.close ()
4) Other Parameters
Serialize obj to a JSON formatted str ( json string representation of the object). 

Skipkeys: The default value is False, if the data is not within the python basic types of keys dict (str, unicode, int, long , float, bool, None) when set to False,
it will report an error TypeError. At this time, provided True, it will skip such Key

ensure_ascii :, when it is True when all non-ASCII characters as \\ uXXXX sequence, only when the dump is set to False ensure_ascii can, at this time json into the Chinese to display properly. )
The If check_circular IS to false, the then The Circular Reference Check for Container types Will BE Skipped and A Circular Reference Will Result in AN
OverflowError (or worse).
The If allow_nan IS to false, the then IT Will BE A a ValueError to the serialize OUT of Range a float values ( NaN3, INF, -INF) in strict The Compliance of the JSON
Specification, The INSTEAD of the using the JavaScript Equivalents (NaN3, Infinity, -Infinity).

indent: it should be a non-negative integer, if 0 is the top grid branches displayed, if the blank is a line most compact display, otherwise it will wrap and the front of the display blank branches displayed in numerical indent of
such printed json data also Printed JSON-called Pretty

separators: separators, actually (item_separator, dict_separator) a tuple, the default is ( ',', ':'); between which is represented by the dictionary keys "," separated,
and between KEY and value with ":" separated.
default (obj) function that Should return IS A A Version of obj or Serializable The raise of The default Simply Raises TypeError TypeError..

sort_keys: the data is sorted according to the value of the keys.
A subclass Custom JSONEncoder use the To (EG One The .DEFAULT The overrides that () Method to the serialize Additional types), with the Specify The CLS IT kwarg;
otherwise JSONEncoder IS Used.

5) the formatted output json
= {Data ' username ' : [ ' Hua ' , ' Erleng child ' ], ' Sex ' : ' MALE ' , ' Age ' : 16 }
json_dic2 = json.dumps(data, sort_keys=True, indent=2, separators=(',', ':'), ensure_ascii=False)
print(json_dic2)
2, json & pickle module 
for serializing the two modules

json, for converting data types between the string and the python
pickle, between the python for specific types and data types of conversion python

pickle module provides four functions : dumps, dump (serialization, deposit), loads (deserialization, reading), load (not only the sequence of the dictionary, list ... python can be any type of data serialization)

. 1) the pickle
. 1  Import the pickle
 2 DIC = { ' K1 ' : ' V1 ' , ' K2 ' : ' V2 ' , ' K3 ' : ' V3 ' }
 . 3 str_dic = the pickle.dumps (DIC)
 . 4  Print (str_dic)   # string of binary content 
. 5  
. 6 DIC2 = The pickle.loads (str_dic)
 . 7  Print (DIC2)     # dictionary 
. 8  
. 9  Import Time
 10 struct_time = time.localtime(1000000000)
11 print(struct_time)
12 f = open('pickle_file', 'wb')
13 pickle.dump(struct_time, f)
14 f.close()
15 
16 f = open('pickle_file', 'rb')
17 struct_time2 = pickle.load(f)
18 print(struct_time2.tm_year)
This time wit you have to say, since the pickle so powerful, why learn json it? 
Here we have to explain, json is a language all can identify data structures.
If we turned it into a dictionary or a sequence json file exists, then the java code or js code can also make use of them.
But if we are serialized with pickle, other languages can not understand what this is -
so, if you serialize the contents of a list or dictionary, we highly recommend that you use json module
but if for some reason you have to the sequence of other data types, and the future of this data you will be deserialized with python, then you can use pickle

Guess you like

Origin www.cnblogs.com/funyou/p/11991815.html
Recommended