python3 (thirty-eight) serialize

"" "   " "" 
__Author__on__ = ' shaozhiqi 2019/9/24 ' 

# / usr / bin / env python3! 
# - * - Coding: UTF-8 - * - 

# program is running, all the variables are in memory, for example, define a dict: 
D = dict (name = ' Bob ' , Age = 20 is, Score = 88 )
 # we variables may be stored or transmitted into the memory from the process is called serialization ** **, called pickling in Python 
# after serialization, you can put the contents of the serialized written to disk, or transferred to other machines over a network. 
# In turn, the variable content from the serialized object to re-read memory called deserialization that unpickling. 
# Python provides a pickle module to achieve serialization. 
Import the pickle 

D = dict (name = ' Bob ' , Age = 20 is, Score = 88 )
the pickle.dumps (D) 
# the pickle.dumps () method of any of the target sequence into a bytes, then this can bytes written to the file. 
# Or the pickle.dump () directly to the target sequence of another write-like method Object File: 
F = Open ( ' dump.txt ' , ' WB ' ) 
the pickle.dump (D, F) 
f.close () 
# to see written dump.txt file, the contents of a bunch of garbage, these are Python objects stored inside information. As follows: 
# } q (the X-nameq the X-Bobq the X-K ageq the X-scoreq KXu??????????. 

# --------------------- -------------- pickle deserialization -------------------------------- ---- 
# when we put an object into memory from disk, you can read the contents of a first bytes, 
# then pickle.loads () method to deserialize the objects, can be directly used pickle.load () the method of file-like Object from a direct deserialize the objects. 
#We open another Python command just saved to deserialize objects: 
F = Open ( ' dump.txt ' , ' RB ' ) 
D = the pickle.load (F) 
f.close () 
Print (D)   # { ' name ':' Bob ',' Age ': 20 is,' Score ': 88} 
# course, the variable and the original variables is completely irrelevant objects, they are just the same as the content of it. 
# 
# Pickle issues and problems specific to serialize all other programming languages, Python is that it can only be used, and may be different versions of Python are not compatible with each other, 
# therefore, can only be saved unimportant data Pickle, We can not successfully deserialize it does not matter. 

# ------------------------------------------ ------ json ---------------------------- 
# if we are to pass objects between different programming languages, it is necessary to serialize objects into standard format, 
# such as XML, but a better approach is serialized to JSON, JSON representation because it is a string,
# Can be read in all languages can be easily stored to disk or transmitted over a network. 
# JSON is not only a standard format, and faster than XML, and can be read directly in a Web page, it is very convenient. 

# The JSON type Python type 
# {} dict 
# [] List 
# "String" STR 
# 1234.56 int or a float 
# to true / to false True / False 
# null None 

# ---------------- -Python Object -> JSON -------------------------------------------- 
Import JSON 

D = dict (name = ' Bob ' , Age = 20 is, Score = 88 ) 
json_d = json.dumps (D)
 Print (json_d)  # { "Name": "Bob", "Age": 20 is, "Score": 88} 
# dumps () method returns a str, content is the standard JSON. Similar, dump () method writes directly to JSON a file-like Object. 

# Should deserialize JSON Python objects, with loads () or a corresponding load () method, the former deserialize JSON string, 
# which reads the character string from the file-like Object and deserialize : 
json_str = ' { "Age": 20 is, "Score": 88, "name": "Bob"} ' 
dictvlaue = json.loads (json_str)
 Print (dictvlaue)
 Print (type (dictvlaue))   # <class' dict '>

But very often, we prefer to represent objects with class, such as the definition of the Student class, then the sequence of: 

Import json 


class Student (Object):
     DEF  __init__ (Self, name, Age, Score): 
        self.name = name 
        self.age = Age 
        self.score = Score 


S = Student ( ' Bob ' , 20 is, 88 ) 


# Print (json.dumps (S)) 
# TypeError: Object of the JSON type Student iS not Serializable 

# cause of the error is not a Student object serialized as JSON objects. 
# Optional parameter default is to put any object can be turned into a sequence of JSON objects, we only need to write a special function to convert Student, then you can pass in a function: 

DEFstudent2dict (STD):
     return {
         ' name ' : std.name,
         ' Age ' : std.age,
         ' Score ' : std.score 
    } 


# Thus, Student first examples student2dict () 
# function into dict, then is successfully serialized to JSON: 
Print (json.dumps (S, default = student2dict))   # { "name": "Bob", "Age": 20, "Score": 88} 

# so the question is, do we each transformed into a class json need to write up a conversion function? 
# Because the instance __dict__ generally has a class attribute, it is a dict, for instance variable storage. 
# There are a few exceptions, such as the definition of the class __slots__. 
Print ( ' Student:, Json.dumps (S, default = the lambda obj: obj. The __dict__ )) 


# Student: { "name": "Bob", "Age": 20 is, "Score": 88} 

# Similarly, if we want JSON deserialize a Student object instance, 
# loads () method first converts a dict objects, then we pass object_hook function is responsible for converting dict Student example: 
DEF dict2student (D):
     return Student (D [ ' name ' ], D [ ' Age ' ], D [ ' Score ' ]) 


json_str = ' { "Age": 20 is, "Score": 88, "name": "Bob"} ' 
STUDENT2 = JSON.loads(json_str, object_hook=dict2student)
print('json-student:', student2.name)  # json-student: Bob

 

Guess you like

Origin www.cnblogs.com/shaozhiqi/p/11580170.html