Use of Json module and Pickle module in Python

angryTom
Release: 2019-11-27 15:21:05
forward
2934 people have browsed it

Use of Json module and Pickle module in Python

Serializing and deserializing data are common data operations. Python provides two modules to facilitate developers to implement data serialization operations, namely json modules and pickle modules. The main differences between these two modules are as follows:

json is a text serialization format, while pickle is a binary serialization format;

json can be read intuitively, but pickle cannot;

json is interoperable and widely used outside the Python system, while pickle is specific to Python;

By default, json can only represent a subset of Python's built-in types. It cannot represent custom classes;

but pickle can represent a large number of Python data types.

Recommended learning: Python video tutorial

Json module

Json is a lightweight data exchange format. Due to its characteristics of small amount of transmitted data and easy parsing of data format, it is widely used in interactive operations between various systems. As a kind of data format to pass data. It contains multiple commonly used functions, as follows:

dumps() function

dumps() function can encode Python objects into Json strings. For example:

#
字典转成json字符串 加上ensure_ascii = False以后, 可以识别中文, indent = 4 是间隔4个空格显示

import json
d = {
    '小明': {
        'sex': '男',
        'addr': '上海',
        'age': 26
    },
    '小红': {
        'sex': '女',
        'addr': '上海',
        'age': 24
    },
}
print(json.dumps(d, ensure_ascii = False, indent = 4))

# 执行结果: {
    "小明": {
        "sex": "男",
        "addr": "上海",
        "age": 26
    },
    "小红": {
        "sex": "女",
        "addr": "上海",
        "age": 24
    }
}
Copy after login

dump() function

dump() function can encode Python objects into json strings and automatically write them to files. No need to Write files separately. For example:

#
字典转成json字符串, 不需要写文件, 自动转成的json字符串写入到‘ users.json’ 的文件中
import json
d = {
    '小明': {
        'sex': '男',
        'addr': '上海',
        'age': 26
    },
    '小红': {
        'sex': '女',
        'addr': '上海',
        'age': 24
    },
}#
打开一个名字为‘ users.json’ 的空文件
fw = open('users.json', 'w', encoding = 'utf-8')

json.dump(d, fw, ensure_ascii = False, indent = 4)
Copy after login

loads() function

loads() function can convert a json string into a Python data type. For example:

#
这是users.json文件中的内容 {
        "小明": {
            "sex": "男",
            "addr": "上海",
            "age": 26
        },
        "小红": {
            "sex": "女",
            "addr": "上海",
            "age": 24
        }
    }

#!/usr/bin / python3# 把json串变成python的数据类型
import json# 打开‘ users.json’ 的json文件
f = open('users.json', 'r', encoding = 'utf-8')# 读文件
res = f.read()
print(json.loads(res))

# 执行结果: {
    '小明': {
        'sex': '男',
        'addr': '上海',
        'age': 26
    },
    '小红': {
        'sex': '女',
        'addr': '上海',
        'age': 24
    }
}
Copy after login

load() function

load() has a similar function to loads(). The load() function can convert a json string into a Python data type. The difference is that the parameter of the former is a file object, and there is no need to read this file separately. For example:

#
把json串变成python的数据类型: 字典, 传一个文件对象, 不需要再单独读文件
import json# 打开文件
f = open('users.json', 'r', encoding = 'utf-8')
print(json.load(f))

# 执行结果: {
    '小明': {
        'sex': '男',
        'addr': '上海',
        'age': 26
    },
    '小红': {
        'sex': '女',
        'addr': '上海',
        'age': 24
    }
}
Copy after login

Pickle module

The Pickle module has similar functions to the Json module and also contains four functions, namely dump(), dumps(), loads() and load(), their main differences are as follows:

The difference between dumps and dump is that the former serializes the object, while the latter serializes the object and saves it to a file. The difference between loads and load is that the former deserializes the serialized string, while the latter reads the serialized string from the file and deserializes it.

dumps() function

dumps() function can convert data in a special form into a string that is only recognized by the python language, for example:

import pickle# dumps功能
import pickle
data = ['A', 'B', 'C', 'D']
print(pickle.dumps(data))

b '\x80\x03]q\x00(X\x01\x00\x00\x00Aq\x01X\x01\x00\x00\x00Bq\x02X\x01\x00\x00\x00Cq\x03X\x01\x00\x00\x00Dq\x04e.'
Copy after login

dump() function

The dump() function can convert data into a string that is only recognized by the python language in a special form and write it to a file. For example:

# dump功能
with open('test.txt', 'wb') as f:
    pickle.dump(data, f)
    print('写入成功')
Copy after login

Write successfully

loads() function

loads() function can convert pickle data into python data structure. For example:

# loads功能
msg = pickle.loads(datastr)
print(msg)
['A', 'B', 'C', 'D']
Copy after login

load() function

The load() function can read data from a data file and convert it into a python data structure. For example:

# load功能with open('test.txt', 'rb') as f:
   data = pickle.load(f)
    print(data)
['A', 'B', 'C', 'D']
Copy after login

This article comes from the python tutorial column, welcome to learn!

The above is the detailed content of Use of Json module and Pickle module in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!