首页 > 编程笔记 > Python笔记 阅读:13

Python json模块的用法(附带实例)

Python 内置了 json 模块,用于处理 JSON 数据与 Python 基础数据的相互转换。

在 json 模块中,有 json.dumps、json.dump、json.loads、json.load 这 4 个主要的函数来实现相关的转换功能。

json 模块的 4 个函数与数据转换的关系如下图所示:


图 1 json 模块的 4 个函数与数据转换的关系

json.dumps()函数

json.dumps 函数的主要功能是将 Python 的数据对象转换为 JSON 数据。读者需要掌握以下 3 个参数:
使用 json.dumps 函数将 Python 数据对象转换为 JSON 数据,例如:
import json
 
python_data = {'name': 'netdevops01', 'ip': '192.168.137.1',
               'vendor': '华为', 'online': True, 'rack': '0101',
               'start_u': 20, 'end_u': 21, 'interface_usage': 0.67,
               'interfaces': ['eth1/1', 'eth1/2', 'eth1/3'],
               'uptime': None}
 
json_text = json.dumps(python_data, ensure_ascii=False, indent=4)
print(type(json_text))
print(json_text)
其输出结果如下:
<class 'str'>
{
    "name": "netdevops01",
    "ip": "192.168.137.1",
    "vendor": "华为",
    "online": true,
    "rack": "0101",
    "start_u": 20,
    "end_u": 21,
    "interface_usage": 0.67,
    "interfaces": [
        "eth1/1",
        "eth1/2",
        "eth1/3"
    ],
    "uptime": null
}

json.dump()函数

json 模块提供了函数 json.dump,它通过调用文件对象的 write 方法,可以将 Python 数据对象转换为 JSON 文本的字符串并写入文件。

读者需要掌握 json.dump 函数的以下 4 个参数:
使用 json.dump() 函数将 Python 数据对象转换为 JSON 文本并写入文本文件,例如:
import json
 
python_data = {'name': 'netdevops01', 'ip': '192.168.137.1',
               'vendor': '华为', 'online': True, 'rack': '0101',
               'start_u': 20, 'end_u': 21, 'interface_usage': 0.67,
               'interfaces': ['eth1/1', 'eth1/2', 'eth1/3'],
               'uptime': None}
with open('data.json', mode='w', encoding='utf8') as f:
    json.dump(python_data, fp=f, ensure_ascii=True, indent=4)
成功运行代码后,在代码所在的目录中会生成一个名为 data.json 的文本文件。

json.loads()函数

json.loads() 函数可以将 JSON 数据转换为 Python 的数据对象。

json.loads() 函数中最重要的参数是第一个参数 s(一般按位置赋值的方式传入实参),用于接收要转换的 JSON 文本字符串。json.loads() 函数将 JSON 数据转换为 Python 数据,例如:
import json
 
json_text = """{
  "name": "netdevops01",
  "ip": "192.168.137.1",
  "vendor": "huawei",
  "online": true,
  "rack": "0101",
  "start_u": 20,
  "end_u": 21,
  "interface_usage": 0.67,
  "interfaces": ["eth1/1","eth1/2","eth1/3"],
  "uptime": null
}"""
data = json.loads(json_text)
print(type(data))
print(data)
其输出结果如下:

<class 'dict'>
{'name': 'netdevops01', 'ip': '192.168.137.1', 'vendor': 'huawei', 'online': True, 'rack': '0101'’, 'start_u': 20, 'end_u': 21, 'interface_usage': 0.67, 'interfaces': ['eth1/1', 'eth1/2', 'eth1/3'], 'uptime': None}

json.load()函数

json.load() 函数将文本文件对象转换为 Python 数据,例如:
import json
 
with open('data.json', encoding='utf8') as f:
    data = json.load(fp=f)
    print(type(data))
    print(data)
输出结果如下:

<class 'dict'>
{'name': 'netdevops01', 'ip': '192.168.137.1', 'vendor': '华为', 'online': True,
'rack': '0101', 'start_u': 20, 'end_u': 21, 'interface_usage': 0.67, 'interfaces':
['eth1/1', 'eth1/2', 'eth1/3'], 'uptime': None}

以上就是 Python 数据对象与 JSON 数据之间相互转换时涉及的 4 个重要函数,其中函数名称中有 s 的函数就是将 Python 数据和 JSON 数据的字符串进行相互转换,没有 s 的函数就是将 Python 数据对象和承载有 JSON 数据的文本文件进行相互转换。

相关文章