Python Data Persistence 简明教程
Python Data Persistence - JSON Module
JSON 的全称是 JavaScript Object Notation 。它是一种轻量级数据交换格式。它是一种独立于语言且跨平台的文本格式,受许多编程语言支持。此格式用于 Web 服务器和客户端之间的交换数据。
JSON stands for JavaScript Object Notation. It is a lightweight data interchange format. It is a language-independent and cross platform text format, supported by many programming languages. This format is used for data exchange between the web server and clients.
JSON 格式类似于 pickle。然而,pickle 序列化是 Python 专用的,而 JSON 格式由许多语言实现,因此已成为通用标准。Python 标准库中的 json 模块的功能和界面类似于 pickle 和 marshal 模块。
JSON format is similar to pickle. However, pickle serialization is Python specific whereas JSON format is implemented by many languages hence has become universal standard. Functionality and interface of json module in Python’s standard library is similar to pickle and marshal modules.
正如同 pickle 模块一样,json 模块还提供了 dumps() 和 loads() 函数,用于将 Python 对象序列化为 JSON 编码字符串, dump() 和 load() 函数将序列化的 Python 对象写入文件/从文件中读取。
Just as in pickle module, the json module also provides dumps() and loads() function for serialization of Python object into JSON encoded string, and dump() and load() functions write and read serialized Python objects to/from file.
-
dumps() − This function converts the object into JSON format.
-
loads() − This function converts a JSON string back to Python object.
下面的示例演示了如何使用这些函数 −
Following example demonstrates basic usage of these functions −
import json
data=['Rakesh',{'marks':(50,60,70)}]
s=json.dumps(data)
json.loads(s)
dumps() 函数可以获取可选的 sort_keys 参数。默认情况下,它为 False。如果设为 True,字典键将按 JSON 字符串中的排序顺序显示。
The dumps() function can take optional sort_keys argument. By default, it is False. If set to True, the dictionary keys appear in sorted order in the JSON string.
dumps() 函数有另一个可选参数,称为 indent,它将数字作为取值。它决定 json 字符串格式化表示的每个部分的长度,类似于打印输出。
The dumps() function has another optional parameter called indent which takes a number as value. It decides length of each segment of formatted representation of json string, similar to print output.
json 模块还具有与上述函数对应的面向对象 API。模块中定义了两个类 – JSONEncoder 和 JSONDecoder。
The json module also has object oriented API corresponding to above functions. There are two classes defined in the module – JSONEncoder and JSONDecoder.
JSONEncoder class
这个类的对象就是 Python 数据结构的编码器。如以下表格所示,每个 Python 数据类型都会转换成对应的 JSON 类型 −
Object of this class is encoder for Python data structures. Each Python data type is converted in corresponding JSON type as shown in following table −
Python |
JSON |
Dict |
object |
list, tuple |
array |
Str |
string |
int, float, int- & float-derived Enums |
number |
True |
true |
False |
false |
None |
null |
JSONEncoder 类由 JSONEncoder() 构造函数实例化。编码器类中定义了以下重要方法 −
The JSONEncoder class is instantiated by JSONEncoder() constructor. Following important methods are defined in encoder class −
Sr.No. |
Methods & Description |
1 |
encode() serializes Python object into JSON format |
2 |
iterencode() Encodes the object and returns an iterator yielding encoded form of each item in the object. |
3 |
indent Determines indent level of encoded string |
4 |
sort_keys is either true or false to make keys appear in sorted order or not. |
5 |
Check_circular if True, check for circular reference in container type object |
以下示例对 Python 列表对象进行编码。
Following example encodes Python list object.
e=json.JSONEncoder()
e.encode(data)
JSONDecoder class
此类的对象有助于将解码的 JSON 字符串还原为 Python 数据结构。此类中的主要方法是 decode()。以下示例代码从早期步骤中的编码字符串中检索 Python 列表对象。
Object of this class helps in decoded in json string back to Python data structure. Main method in this class is decode(). Following example code retrieves Python list object from encoded string in earlier step.
d=json.JSONDecoder()
d.decode(s)
json 模块定义了 load() 和 dump() 函数,用于将 JSON 数据写入到磁盘文件或字节流等文件对象中,并从中读取数据。
The json module defines load() and dump() functions to write JSON data to a file like object – which may be a disk file or a byte stream and read data back from them.
dump()
此函数将 JSON 的 Python 对象数据写入文件。此文件必须使用“w”模式打开。
This function writes JSONed Python object data to a file. The file must be opened with ‘w’ mode.
import json
data=['Rakesh', {'marks': (50, 60, 70)}]
fp=open('json.txt','w')
json.dump(data,fp)
fp.close()
此代码将在当前目录中创建“json.txt”。它显示的内容如下:
This code will create ‘json.txt’ in current directory. It shows the contents as follows −
["Rakesh", {"marks": [50, 60, 70]}]
load()
此函数从文件中加载 JSON 数据并从中返回 Python 对象。此文件必须使用读取权限(应具有“r”模式)打开。
This function loads JSON data from the file and returns Python object from it. The file must be opened with read permission (should have ‘r’ mode).
Example
fp=open('json.txt','r')
ret=json.load(fp)
print (ret)
fp.close()
Output
['Rakesh', {'marks': [50, 60, 70]}]
json.tool 模块还有一个命令行界面,用于验证文件中的数据并以漂亮的格式打印 JSON 对象。
The json.tool module also has a command-line interface that validates data in file and prints JSON object in a pretty formatted manner.
C:\python37>python -m json.tool json.txt
[
"Rakesh",
{
"marks": [
50,
60,
70
]
}
]