Python serialization module JSON and Pickle

Source: Internet
Author: User

Serialization related 1. Json
    • Application Scenarios:

The JSON module is primarily used to process data in JSON format, can convert JSON-formatted data into a Python dictionary, facilitates python processing, and can convert objects such as a Python dictionary or list into JSON-formatted data for cross-platform or cross-language data interaction

  • Function:

      • The JSON module provides four functions: dumps, dump, loads, load

      • Python encoding is a JSON type conversion table:

    Python JSON
    Dict Object
    List, tuple Array
    Str String
    int, float, int-& float-derived Enums number|
    True True
    False False
    None Null
      • JSON decodes the corresponding table for the Python type conversion:
    JSON Python
    Object Dict
    Array List
    String Str
    Number (int) Int
    Number (real) Float
    True True
    False False
    Null None
  • Specific applications

      • Dumps and loads for serializing and deserializing between Python objects and strings

    Dumps: Convert python base data type to JSON format data type
    Loads: Converting JSON format data types to Python data types

    #!/usr/bin/env python#-*-coding:utf-8-*-#pyversion:python3.5#Owner:fuzjImportjsons1='{"Key1": "Value1"}'      #The string can only be in this format before it can be deserialized by the JSON conversion through loads, you must use double quotation marksD1= {'Key2':'value2'}s2=json.loads (S1) # using loads deserializationPrint('content of S1:', S1)Print("type of S1:", type (S1))Print('content of S2:', S2)Print("type of S2:", type (s2)) D2=json.dumps (D1)Print('content of D1:', D1)Print("type of D1:", type (D1))Print('content of D2:', D2)Print("Types of D2", type (D2))

    Output: S1 content: {"Key1":"value1"type of}S1:<class 'Str'>contents of S2: {'Key1':'value1'type of}S2:<class 'Dict'># After processing by loads, str stale DICTD1 content: {'Key2':'value2'type of}D1:<class 'Dict'>contents of D2: {"Key2":"value2"Types of}d2<class 'Str'> # after dumps processing, dict becomes STR

      • Dump and load are used for serializing and deserializing files

    Dump: Mainly used for reading and writing JSON files, Json.dump (x,f), X is an object, F is a file object, this method can write a JSON string into a text file
    Load: Load JSON file

    ```#!/usr/bin/env python#-*-coding:utf-8-*-#pyversion:python3.5#Owner:fuzjImportjsons1='{"Key1": "Value1"}'      #The string can only be in this format before it can be deserialized by the JSON conversion through loads, you must use double quotation marksD1 = {'Key2':'value2'}json.dump (D1,open ('serializing. txt','W') # Serializes the S1 and writes to the file E1= Json.load (Open ('serializing. txt','R') # Read JSON filePrint("type of E1:", type (e1))Print('content of E1:', E1) "Output: Type of E1:<class 'Dict'>contents of E1: {'Key2':'value2'}

2. Pickle
    • Application Scenarios

The Pickle module implements basic data sequence and deserialization, similar to the functionality of JSON.
Through the serialization of the Pickle module we can save the object information running in the program to a file, store it permanently, or simply serialize the character.
Through the deserialization of the Pickle module, we were able to create the last object saved by the program from the file, or to deserialize the character. Unlike JSON: JSON is more suitable for cross-language processing of strings, basic data types; Pickle python proprietary, more suitable for handling complex types of serialization

  • Function
    The Pikle module provides the basic functions of the dumps loads dump load four

  • Specific applications

      • Dumps and loads for serializing and deserializing between Python objects and strings

    Dumps and Json.dumps functions, but returns encapsulated objects as byte objects
    Like the loads and json.loads functions, the encapsulated object is read from the byte object and returned

    #!/usr/bin/env python#-*-coding:utf-8-*-#pyversion:python3.5#Owner:fuzjImportpickles1='{"Key1": "Value1"}'      #The string can only be in this format before it can be deserialized by the JSON conversion through loads, you must use double quotation marksD1= {'Key2':'value2'}S3=pickle.dumps (S1)Print('content of S1:', S1)Print("type of S1:", type (S1))Print('content of S3:', S3)Print("type of S3:", type (S3)) D3=pickle.loads (S3)Print('content of D1:', D1)Print("type of D1:", type (D1))Print('content of D3:', D3)Print("Types of D3", type (d3)) output result: S1 content: {"Key1":"value1"type of}S1:<class 'Str'>content of S3: B'\x80\x03x\x11\x00\x00\x00{"Key1": "Value1"}q\x00.'type of S3:<class 'bytes'>The contents of the byte type D1 are returned after #dumps processing: {'Key2':'value2'type of}D1:<class 'Dict'>contents of D3: {"Key1":"value1"Types of}d3<class 'Str'>

      • Dump and load are used to serialize and deserialize files. Python data persistence is more

        • Pickle.dump (obj, file, [, Protocol])
          Note: Save the object, obj, to file.
          Protocol is the protocol version used for serialization, the 0:ASCII protocol, the serialized object is represented by printable ASCII code, 1: The old binary protocol, and the new binary protocol introduced by version 2:2.3, which is more efficient than the previous ones. where protocols 0 and 1 are compatible with older versions of Python. The default value for protocol is 0.
          File: Object to which the class files are saved. File must have a write () interface, file can be an open with a ' W ' method or an Stringio object or any other object that implements the write () interface. If protocol>=1, the file object needs to be opened in binary mode.

        • Pickle.load (file)
          Note: Reads a string from file and reconstructs it as the original Python object.
          File: Class files object with Read () and ReadLine () interfaces

    #!/usr/bin/env python#-*-coding:utf-8-*-#pyversion:python3.5#Owner:fuzjImportJSONImportpickles1='{"Key1": "Value1"}'      #The string can only be in this format before it can be deserialized by the JSON conversion through loads, you must use double quotation marksD1= {'Key2':'value2'}pickle.dump (S1,open ('serializing. txt','WB'))#Note that you need to write the file in binary modeE2 = pickle.load (open ('serializing. txt','RB'))#you need to read the file in binary modePrint("type of E2:", type (e2))Print('content of E2:', E2) output result: Type of E2:<class 'Str'>contents of E2: {"Key1":"value1"}

Python serialization module JSON and Pickle

Related Article

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.