For Python, these two modules are a very useful two module for storing data instances in a simple way.
Pickle Module
provided to store python various data serialization stores # The original Cpickle already in Python3 with pickle merge dumps (obj) returns object information stored in binary string loads (str) Returns the object information of the binary string Dump (obj, file) writes object information to a binary file, including the basic data structure, the function instance, and the class instance load (file) reads a stored object from the binary file in the same order as the write order import pickle >>& Gt d {' age ': +, ' name ': ' BOB ', ' degree ': ' Master '} >>> work = (1, 2, 3) >>> Pickle.dumps (d) b ' \x80\x03}q\x00 (x\x03\x00\x00\x00ageq\x01kdx\x04\x00\x00\x00nameq\x02x\x03\x00\x00\x00bobq\x03x\x06\x00\x00\ x00degreeq\x04x\x06\x00\x00\x00masterq\x05u. ' >>> Pickle.dumps (work) b ' \x80\x03k\x01k\x02k\x03\x87q\x00. ' >>> f = open (' Test.txt ', ' WB ') >>> pickle.dump (d,f) >>> pickle.dump (work,f) >>&G T F.close () >>> f = open (' Test.txt ', ' RB ') >>> Pickle.load (f) {' age ': +, ' name ': ' BOB ', ' degree ': ' Master '} >>> Work2 = Pickle.load (f) >>> Work2 (All-in-all) >>> pickle.load (f) EOF Error:ran out of input
JSON module
Similar to the Pickle module, but the stored data type is not binary based, but the data format used for text pickle is Python-specific, and JSON is designed to be used across languages
Note: The following sections are transferred from the official website of Liaoche
JSON type Python type {} dict [] list "string" ' str ' or U ' Unicode ' 1234.56 int or float true/false True/false null None python's built-in JSON module provides a very complete translation of Python objects into JSON format. Let's take a look at how to turn the Python object into a JSON: >>> import json >>> d = dict (name= ' Bob ', age=20, score=88) >&G T;> Json.dumps (d) ' {"Age": $, "score":, "name": "Bob"} ' dumps () method returns a str with the content being the standard JSON. Similarly, the dump () method can write JSON directly to a file-like Object. To deserialize JSON into a Python object, use the loads () or the corresponding load () method to deserialize the JSON string, which reads the string from the File-like object and deserializes it: >>> json_str = ' {"Age": +, "score": "," "Name": "Bob"} ' >>> json.loads (json_str) {' Age ': ' Score ': ", ' name ': ' Bob '} Python's Dict object can be serialized directly into the JSON {}, but, many times, we prefer to use class to represent objects, such as defining the Student class, and then serializing: Import JSON class Student (object): def __init__ (self, name, age, score): Self.name = name Self.age = Age Self.score = Score s = Student (' Bob ', +, +) print (JSON.DUmps (s)) runs the code and relentlessly gets a typeerror:typeerror: <__main__. The Student object at 0x10aabef50> was not a JSON serializable error because the Student object was not an object that could be serialized as JSON. If the instance object of a class cannot be serialized as JSON, this is certainly unreasonable! Don't worry, let's take a closer look at the parameter list of the dumps () method, you can see that the dumps () method provides a whole bunch of optional parameters in addition to the first required obj parameter: These optional parameters let us customize JSON serialization. The previous code was unable to serialize the student class instance to JSON because, by default, the dumps () method did not know how to make the student instance a JSON {} object. Optional parameter The default is to turn any object into an object that can be serialized as JSON, we just need to write a conversion function for student, and then pass the function in: def student2dict (STD): return { ' Name ': Std.name, ' age ': std.age, ' score ': Std.score} print (Json.dumps (S, default=st udent2dict)) In this way, the student instance is first converted to Dict by the student2dict () function and then successfully serialized as JSON. However, the next time you encounter an instance of a teacher class, you cannot serialize to JSON. We can steal a lazy, turn an instance of any class into Dict:print (Json.dumps (S, Default=lambda obj:obj.__dict__)) because the instance of class usually has a __dict__ attribute, which is A dict that is used to store instance variables. There are a few exceptions, such as defining the class of __slots__. Similarly, if we are going to deserialize JSON into a student object instance, the loads () method first converts a Dict object, and then the Object_hook function we pass in is responsible for converting dict toStudent Example: Def dict2student (d): Return Student (d[' name '), d[' age ', d[' score ']) Json_str = ' {' Age ': 2 0, "score": "A", "name": "Bob"} ' Print (Json.loads (JSON_STR, object_hook=dict2student)) The result of the operation is as follows: <__main__. Student object at 0x10cd3c190> prints out the deserialized Student instance object.
Because JSON and pickle modules can only save class instances, function instances, sequences, and so on, and cannot save classes, functions. Presumably because these classes or functions can be imported as a package/module, and the two modules are imported as data for their actual objects, they do not interfere with each other.
Python3 learning the 12th bullet: module Learning pickle and JSON