Python route -14. Json & Pickle Data serialization

Source: Internet
Author: User
Tags serialization

Serialization of 14.1

Example 1:

#! Author:lanhan
#把字典的内存数据类型通过字符串存到硬盘上 (json.dumps) , only strings, lists, dictionaries, etc. are processed
Import JSON
info = {
' name ':' Lanhan ',
' age ': 22
}
f = open ("test.txt","W")
Print (Json.dumps (info))
F.write (Json.dumps (info))
F.close ()

Example 2: pickle can handle complex, such as functions

Import Pickle
def Sayhi (name):
Print ("Hello", name)
info = {
' name ':' Lanhan ',
' age ': 22,
' func ': Sayhi
}
f = open ("test.txt","WB")
F.write (Pickle.dumps (info))

Example 3:

Import JSON
def Sayhi (name):
Print ("Hello", name)
info = {
' name ':' Lanhan ',
' age ': 22
}
f = open ("test.txt","W")
F.write (Json.dumps (info))
info[' age '] = 21
F.write (Json.dumps (info))
F.close ()

14.2 Deserialization

Example 1:

#! Author:lanhan
#把硬盘的数据类型恢复到内存中 (json.loads) , only strings, lists, dictionaries, etc. are processed
Import JSON
f = open ("test.txt","R")
data = Json.loads (F.read ())
F.close ()
Print (data["age"])

Example 2:pickle can handle complex, such as functions

# #pickle

Import Pickle
def Sayhi (name):
Print ("Hello", name)
Print ("Hello2", name)
f = open ("test.txt","RB")
data = Pickle.load (f) ###==== #data = Pickle.loads (F.read ())

Print (data["func"] ("Lanhan"))

Example 3:

#! Author:lanhan
#c错误的, indicating that there are multiple states can dump multiple times, not multiple loads, that is, there are multiple states dump multiple files, dump once, load once
Import JSON
f = open ("test.txt","R")
for line in F:
Print (Json.loads (line))
Print (data)

Python route -14. Json & Pickle Data serialization

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.