JSON module, pickle module, shelve module

Source: Internet
Author: User


First, what is called serialization
The process of converting an original dictionary, list, and other content into a string is called serialization.

Second, the purpose of serialization
1. Persist the custom object in some form of storage;
2. Transfer objects from one place to another.
3, make the program more maintenance.

Three
Only strings can be written to the file
Only bytes---strings that can be transmitted over the network
Converts the content to be transmitted and the contents to be stored into characters
String conversion back to the content to be transferred and stored


Iv. there are only two functions of serialization
Network transmission
Data Persistence-written in a file


Five, JSON module
JSON is common to all languages, data types

1. Transmission on the network, more frequent
RET = json.dumps (data structure)
Print (Json.loads (ret))

2.dump,load used in the serialization and deserialization of the file's Operation data type
Json.dump (data structure, file F)
Json.load (f)

               Dumps,dump (serialized) dictionary, List  ---------------------------"string                loads, load (deserialization)

Note: Tuples are equivalent to serialization of lists, but they are not generally used

example 1:dumps,loads examples D= {' Key1 ': ' Values1 ',' key2 ': ' Values2 '}ret= Json.dumps (d)Print(d,type(ret)) #<class ' str ' >Print(Json.loads (ret),type(Json.loads (ret))) #<class ' Dict ' >Example 2:dump,The load example serializes and then writes only one dictionary with open("Log", "W", encoding= "Utf-8")As F1:json. Dump (D,f1,ensure_ascii=false) #True Chinese is written in GBK and written in the form of with open("Log", "R", encoding= "Utf-8")As F1: forLine in F1:Print(Json.loads (Line.strip ()))example 3:ensure_ascii keyword parameter data= {' username ': [' Li Hua ', ' Erlengzi '], ' sex ': ' Male ', ' age ': 16}with Open("Log", "W", encoding= "Utf-8")As F1:json. Dump (Data,f1,ensure_ascii=false)With Open("Log", "R", encoding= "Utf-8")As F1:Print(Json.load (F1))Example 4: Formatted output data= {' username ': [' Li Hua ', ' Erlengzi '], ' sex ': ' Male ', ' age ': 16}# (data structure, flashback, number of spaces in front, "," instead of ",")Json_dic2= Json.dumps (data,sort_keys=true,indent=10,separators= (', ', ': '), Ensure_ascii=false)Print(JSON_DIC2)

Liu, Pickle

Two module JSON for serialization, for converting between string and Python data types
Pickle for conversion between Python-specific types and Python data types
The Pickle module provides four functions: dumps, dump (serialization, Save),
Loads (deserialization, read), load (can not only serialize dictionary, list ...) Can serialize arbitrary data types in Python)

Example 1:dumps,loadsdic= {' K1 ': ' v1 ', ' K2 ': ' V2 ',' K3 ': ' V3 '}str_dic= Pickle.dumps (DIC)Print(str_dic) #A string of binary content Dic2= Pickle.loads (Str_dic)Print(DIC2) #DictionaryExample 2:dump loadimport TimeS_time= Time. LocalTime (1000000000)Print(S_time)With Open("Log", "WB")As f1:s_time= Pickle.dump (S_TIME,F1)With Open("Log", "RB")As f1:s_time2= Pickle.load (F1)Print(s_time2)Example 3:dump loaddic= {' K1 ': ' v1 ', ' K2 ': ' V2 ',' K3 ': ' V3 '}with open("Log", "WB")As F1:pickle. Dump (DIC,F1)Pickle. Dump (DIC, F1)With Open("Log", "RB")As F1:Print(Pickle.load (F1))Print(Pickle.load (F1))

Seven,  the difference between JSON and pickle

1.pickle module dumps followed by bytes
The contents of the 2.pickle module dump are messy in the file.
3.pickle module can continuously dump data into the file and then load it continuously.
4.pickle can arbitrarily serialize data types in Python
JSON can only serialize a list dictionary

Class A:pass # Program
A = A ()
b = Pickle.dumps (a)
Print (b)
Print (Pickle.loads (b))
Eight, shelve

Shelve is also a serialization tool provided to us by Python, which is simpler to use than pickle.
Shelve only provides us with an open method, which is accessed using key and is similar to a dictionary.
(Access and access)
Import Shelvewith Shelve. Open (' Shelve_file ')As f1:f1[' key ']= {' int ': Ten, ' float ': 9.5, ' string ': ' Sample data '} #directly to the file handle, you can deposit data with shelve. Open (' Shelve_file ')As f1:existing= f1[' key '] #when you take out the data, you just need to get it directly with the key, but if the key doesn't exist, it willPrint(existing) # key:{' int ': Ten, ' float ': 9.5,' string ': ' Sample data '}with shelve. Open (' Shelve_file ', writeback=true)As f1:f1[' key ' [' New_value ']= ' This is notHere before ' with shelve. Open (' Shelve_file ')As F1:Print(f1[' key ']) # {' int ': Ten, ' float ': 9.5, ' string ': ' Sample data ', ' new_value ': ' This is notHere before '}

JSON module, pickle module, shelve 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.