Python module knowledge 4: serialization of Json/pickle and jsonpickle

Source: Internet
Author: User

Python module knowledge 4: serialization of Json/pickle and jsonpickle

Serialization and deserialization

Serialization: converts the basic data type of Python to a string.

Deserialization: converts a string to the basic data type of Python.


Two modules used for serialization in Python:

  • Json is used for conversion between [String] and [python basic data type]. Because the string is common in various languages, json is more suitable for cross-language conversion; however, only dict, list, tuple, str, int, flost, True, and False are supported.

  • Pickle is used for conversion between [python-specific types] and [python Basic Data Types]. It supports all types and is more suitable for all types of serialization, such as object-oriented

The Json module provides four functions: dumps, dump, loads, and load.

The pickle module provides four functions: dumps, dump, loads, and load.


About json:

  • JSON: JavaScript Object Notation (JavaScript Object Notation ).

  • JSON is the syntax for storing and exchanging text information. Similar to XML.

  • JSON is smaller, faster, and easier to parse than XML


Case 1: Double quotation marks (such as li = ["a", "B"]) must be used when strings are involved in the dumps and loads json conversion process. instead of li = ['A', 'B']

Import json
Dic = {"k1": "v1", "k2": "v2 "}
Print ('dic ', dic, type (dic ))
Result = json. dumps (dic) # convert the basic python data type to a string
Print ('result', result, type (result ))
Dic2 = json. loads (result) # convert a string to a basic data type,
Print ('dic2', dic2, type (dic2 ))

Execution result:

Case 2: Reading and Writing data in json, dump, load

Import json
Li = ["a", "B"]
Json. dump (li, open ('db', 'w') # execution result. li content is written to the db file.
R = json. load (open ('db', 'R') # file read Operations
Print (r, type (r ))

Execution result:

['a', 'b'] <class 'list'>

Case 3: Obtain weather-related json data using the weather API

Import requests
Import json
R = requests. get ('HTTP: // wthrcdn.etouch.cn/weather_mini? City = Beijing ')
R. encoding = 'utf-8'
Dic = json. loads (r. text)
Print (dic)

Execution result:


Application of pickle:


Case 4: dumps and loads of pickle

Import pickle
Dic = {"k1": "v1", "k2": "v2 "}
Print ('dic ', dic, type (dic ))
Result = pickle. dumps (dic) # convert the basic python data type into bytes
Print ('result', result, type (result ))
Dic2 = pickle. loads (result) # convert string to basic data type
Print ('dic2', dic2, type (dic2 ))

Execution result:


Case 5-1: pickle writes and exports files. type must be added with B

Import pickle

Li = ["a", "B"]
Pickle. dump (li, open ('hh', 'wb') # Add B to the type
R = pickle. load (open ('hh', 'rb') # to read a file, add B
Print (r, type (r ))

Execution result:

Case 5-2: modify the content of the import File

Import pickle
Account_info = {'a1': ['hh', 222,20],
'A2 ': ['rr', 444,40]
}
Pickle. dump (account_info, open ('Acc. pkl', 'wb '))
T = pickle. load (open ('Acc. pkl', 'rb '))
Print ('first import', t, type (t ))

# Modify a value in the dictionary, store it again, and call
Account_info ['a2 '] [1] = 555
Account_info ['a2 '] [2] = 50
Pickle. dump (account_info, open ('Acc. pkl', 'wb '))
F = pickle. load (open ('Acc. pkl', 'rb '))
Print ("Modify value", f, type (f ))
# Add a new field
Account_info ['a3 '] = ['ppp', 666, 60]
Pickle. dump (account_info, open ('Acc. pkl', 'wb '))
Y = pickle. load (open ('Acc. pkl', 'rb '))
Print ("Add new value", y, type (y ))


Case 5-3: How to Use pickle of an object

Case 5-4: Use pickle on jupyter

New_data.to_pickle ('C: \ data_0921.pickle ')

New_data = pd. read_pickle ('C: \ data_0921.pickle ')


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.