Python 中的 JSON:全面指南
JSON(JavaScript 对象表示法)是一种与语言无关的数据交换格式,广泛用于在客户端和服务器之间传输数据。Python 通过多个模块支持 JSON,其中“json”和“simplejson”最为流行。
Python 内置的“json”模块提供读取和写入 JSON 文件的方法。“json.load()”方法用于从文件中读取 JSON 数据,“json.dump()”方法用于将 JSON 数据写入文件。
Python 对象可以通过序列化过程转换为 JSON 格式,使用“json.dump()”或“json.dumps()”方法。相反,JSON 数据可以通过反序列化过程转换回 Python 对象,使用“json.load()”或“json.loads()”方法。
Python 和 JSON 数据类型具有等效项。例如,Python 的“dict”等效于 JSON 的“object”,而 Python 的“list”或“tuple”等效于 JSON 的“array”。此映射有助于 Python 和 JSON 之间的转换过程。
在本教程中,我们将学习如何使用相关的示例在 Python 中读取、写入和解析 JSON。我们还将探讨 Python 中用于处理 JSON 的常用模块。
JSON 是一种轻量级的数据交换格式。它是用于在客户端和服务器之间传输和接收数据的常用格式。但是,它的应用和用途不仅仅限于传输数据。机器可以轻松生成和解析 JSON 数据。JSON 首字母缩写词代表 JavaScript 对象表示法,顾名思义,它是 JavaScript 编程语言的一个子集。
JSON 是一种标准化的数据交换格式,并且与语言无关。几乎所有编程语言都以某种方式支持它。它具有以下结构:
下面是一个 JSON 对象的片段:
<code class="language-json">{ "name": "Chinedu Obi", "age": 24, "country": "Nigeria", "languages": [ "Igbo", "English", "Yoruba" ], "marital status": "single", "employee": true, "experience": [ { "title": "Frontend Engineering Intern", "company": "Andela" }, { "title": "Frontend Engineer", "company": "Paystack" } ] }</code>
为了以后的代码示例的目的,我们将假设上述 JSON 存储在一个名为 employee.json 的文件中。
JSON 数据类型
在使用 JSON 对象时,Python 会将 JSON 数据类型转换为其等效项,反之亦然。下表显示了 Python 数据类型及其 JSON 等效项。
Python | JSON 等效项 |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, long | number |
True | true |
False | false |
None | null |
Python 中 json 和 simplejson 模块的区别
Python 中有几个模块用于编码和解码 JSON。两个最流行的模块是 json 和 simplejson。json 模块是 Python 标准库中的内置包,这意味着我们可以直接使用它,无需安装。
simplejson 模块是用于编码和解码 JSON 的外部 Python 模块。它是一个开源包,与 Python 2.5 和 Python 3.3 向后兼容。它还快速、简单、正确且可扩展。
simplejson 更新更频繁,比 json 具有更新的优化,使其速度更快。如果您在遗留项目中使用的是低于 2.6 的旧版 Python,那么 simplejson 是您的最佳选择。
在本教程中,我们将坚持使用 json 模块。
如何在 Python 中读取和写入 JSON 文件
在使用 Python 编程时,我们经常会遇到 JSON 数据格式,了解如何读取或写入 JSON 数据和文件非常重要。此处对 Python 中文件处理的预先了解将有助于读取和写入 JSON 文件。
与 Python 中的每个其他读取操作一样,with 语句可以与 json.load() 方法一起使用来读取 JSON 文件。
请参见下面的代码示例:
<code class="language-json">{ "name": "Chinedu Obi", "age": 24, "country": "Nigeria", "languages": [ "Igbo", "English", "Yoruba" ], "marital status": "single", "employee": true, "experience": [ { "title": "Frontend Engineering Intern", "company": "Andela" }, { "title": "Frontend Engineer", "company": "Paystack" } ] }</code>
以下是上面代码的输出:
<code class="language-python">import json with open('employee.json', 'r', encoding='utf-8') as file_object: employee_dict = json.load(file_object) print(employee_dict)</code>
在上面的代码中,我们以读取模式打开 employee.json 文件。json.load() 方法将 JSON 数据解码为存储在 employee_dict 变量中的 Python 字典。
我们还可以对 Python 中的文件执行 JSON 数据的写入操作。与读取操作一样,我们使用 with 语句和 json.dump() 方法将 JSON 数据写入文件。
考虑下面的代码片段:
<code>{'name': 'Chinedu Obi', 'age': 24, 'country': 'Nigeria', 'languages': ['Igbo', 'English', 'Yoruba'], 'marital status': 'single', 'employee': True, 'experience': [{'title': 'Frontend Engineering Intern', 'company': 'Andela'}, {'title': 'Frontend Engineer', 'company': 'Paystack'}]}</code>
在这里,我们创建一个 Python 字典 mother,其中包含有关虚构母亲的数据。我们以写入模式打开 mother.json。由于没有这样的文件,因此会为我们创建一个文件。json.dump() 方法将分配给 mother 变量的 Python 字典编码为 JSON 等效项,该等效项将写入指定的文件。执行上述代码后,将出现在我们文件夹根目录中,其中包含 JSON 数据的 mother.json 文件。
如何将 Python 字典转换为 JSON(序列化)
序列化是将 Python 对象(在大多数情况下是字典)转换为 JSON 格式化数据或字符串的过程。序列化时,Python 类型将编码为 JSON 等效项。json 模块提供两种方法——json.dump() 和 json.dumps()——用于将 Python 对象序列化为 JSON 格式。
请注意以下语法:
<code class="language-python">import json mother = { "name": "Asake Babatunde", "age": 28, "marital status": "Married", "children": ["Ayo", "Tolu", "Simi"], "staff": False, "next of kin": {"name": "Babatune Lanre", "relationship": "husband"}, } with open("mother.json", "w", encoding="utf-8") as file_handle: json.dump(mother, file_handle, indent=4)</code>
<code class="language-python">json.dump(obj, fp, indent)</code>
json.dump() 方法有一个参数 fp,而 json.dumps() 没有。
一些参数解释:
让我们将 Python 对象编码为等效的 JSON 格式化数据并将其写入文件。
首先,我们创建一个 Python 字典:
<code class="language-json">{ "name": "Chinedu Obi", "age": 24, "country": "Nigeria", "languages": [ "Igbo", "English", "Yoruba" ], "marital status": "single", "employee": true, "experience": [ { "title": "Frontend Engineering Intern", "company": "Andela" }, { "title": "Frontend Engineer", "company": "Paystack" } ] }</code>
让我们将我们的字典编码为 JSON 数据并写入文件:
<code class="language-python">import json with open('employee.json', 'r', encoding='utf-8') as file_object: employee_dict = json.load(file_object) print(employee_dict)</code>
在上面的示例中,我们将字典、文件指针和缩进参数传递给 json.dump 方法。以下是我们代码的输出。执行代码后,在我们的项目根文件夹中会找到包含预期 JSON 数据的 subject.json 文件:
<code>{'name': 'Chinedu Obi', 'age': 24, 'country': 'Nigeria', 'languages': ['Igbo', 'English', 'Yoruba'], 'marital status': 'single', 'employee': True, 'experience': [{'title': 'Frontend Engineering Intern', 'company': 'Andela'}, {'title': 'Frontend Engineer', 'company': 'Paystack'}]}</code>
我们的输出具有漂亮的打印输出,因为我们添加了值为 4 的缩进参数。
在此示例中,我们将 Python 对象编码为 JSON 字符串。我们之前创建了一个 subject 字典,因此我们可以在此处重复使用它。
让我们以 json.dumps() 方法为例:
<code class="language-python">import json mother = { "name": "Asake Babatunde", "age": 28, "marital status": "Married", "children": ["Ayo", "Tolu", "Simi"], "staff": False, "next of kin": {"name": "Babatune Lanre", "relationship": "husband"}, } with open("mother.json", "w", encoding="utf-8") as file_handle: json.dump(mother, file_handle, indent=4)</code>
以下是上面代码的输出:
<code class="language-python">json.dump(obj, fp, indent)</code>
如前所述,json.dumps() 方法用于将 Python 对象转换为 JSON 格式的字符串。我们可以从控制台中看到我们的 JSON 数据的类型为 str。
如何将 JSON 转换为 Python 字典(反序列化)
JSON 的反序列化是将 JSON 对象解码为等效的 Python 对象或 Python 类型。我们可以使用 json 模块提供的两种方法——json.load() 和 json.loads()——将 JSON 格式化数据转换为 Python 对象。
请注意以下语法:
<code class="language-python">json.dumps(obj, indent)</code>
<code class="language-python">import json subject = { "name": "Biology", "teacher": {"name": "Nana Ama", "sex": "female"}, "students_size": 24, "elective": True, "lesson days": ["Tuesday", "Friday"], }</code>
json.dump() 有一个参数 fp,而 json.dumps() 有一个参数 s。其他参数保持不变。
一些参数解释:
以下是名为 students.json 的新 JSON 文件的内容:
<code class="language-python">with open('subject.json', 'w', encoding='utf-8') as file_handle: json.dump(subject, file_handle, indent=4)</code>
在此示例中,我们将从 students.json 文件解码 JSON 数据到 Python 对象:
<code class="language-json">{ "name": "Biology", "teacher": { "name": "Nana Ama", "sex": "female" }, "students_size": 24, "elective": true, "lesson days": [ "Tuesday", "Friday" ] }</code>
以下是上面代码的输出:
<code class="language-python">json_data = json.dumps(subject, indent=4) print(json_data) print(type(json_data))</code>
在上面的代码片段中,正在解析包含学生列表的 JSON 文件。来自 file_handle 文件的 JSON 数据将传递给 json.load() 方法,该方法将其解码为 Python 字典列表。然后将列表项打印到控制台。
在此示例中,让我们从 JSONPlaceholder 解码来自 API 端点的 JSON 数据。在继续此示例之前,应安装 requests 模块:
<code class="language-json">{ "name": "Chinedu Obi", "age": 24, "country": "Nigeria", "languages": [ "Igbo", "English", "Yoruba" ], "marital status": "single", "employee": true, "experience": [ { "title": "Frontend Engineering Intern", "company": "Andela" }, { "title": "Frontend Engineer", "company": "Paystack" } ] }</code>
以下是上面代码的输出:
<code class="language-python">import json with open('employee.json', 'r', encoding='utf-8') as file_object: employee_dict = json.load(file_object) print(employee_dict)</code>
在上面的 Python 代码中,我们从返回 JSON 格式化字符串的端点获取响应。我们将响应作为参数传递给 json.loads() 方法,将其解码为 Python 字典。
结论
在现代 Web 开发中,JSON 是在服务器和 Web 应用程序之间交换数据的实际格式。如今,REST API 端点返回 JSON 格式的数据,因此了解如何使用 JSON 非常重要。
Python 具有 json 和 simplejson 等模块,用于读取、写入和解析 JSON。json 模块随 Python 标准库一起提供,而 simplejson 是一个外部包,必须在使用前安装。
在 Python 中构建 RESTful API 或在我们的项目中使用外部 API 时,我们经常需要将 Python 对象序列化为 JSON 并将其反序列化回 Python。本文中演示的方法被许多流行的项目使用。步骤通常相同。
(本教程的代码可在 GitHub 上找到。)
关于 Python 中 JSON 的常见问题解答 (FAQ)
由于 json 模块,在 Python 中解析 JSON 是一个简单的过程。您可以使用 json.loads() 函数解析 JSON 字符串。这是一个例子:
<code>{'name': 'Chinedu Obi', 'age': 24, 'country': 'Nigeria', 'languages': ['Igbo', 'English', 'Yoruba'], 'marital status': 'single', 'employee': True, 'experience': [{'title': 'Frontend Engineering Intern', 'company': 'Andela'}, {'title': 'Frontend Engineer', 'company': 'Paystack'}]}</code>
在此代码中,json.loads() 将 JSON 字符串转换为 Python 字典,然后您可以像处理任何其他字典一样与它交互。
json 模块提供 json.dumps() 函数,该函数可以将 Python 对象转换为 JSON 字符串。这是一个例子:
<code class="language-python">import json mother = { "name": "Asake Babatunde", "age": 28, "marital status": "Married", "children": ["Ayo", "Tolu", "Simi"], "staff": False, "next of kin": {"name": "Babatune Lanre", "relationship": "husband"}, } with open("mother.json", "w", encoding="utf-8") as file_handle: json.dump(mother, file_handle, indent=4)</code>
在此代码中,json.dumps() 将 Python 字典转换为 JSON 字符串。
您可以使用 json.load() 函数从文件读取 JSON 数据。这是一个例子:
<code class="language-python">json.dump(obj, fp, indent)</code>
在此代码中,json.load() 读取文件并将 JSON 数据转换为 Python 对象。
您可以使用 json.dump() 函数将 JSON 数据写入文件。这是一个例子:
<code class="language-python">json.dumps(obj, indent)</code>
在此代码中,json.dump() 将 Python 对象作为 JSON 数据写入文件。
json.dumps() 函数提供漂亮打印 JSON 的选项。这是一个例子:
<code class="language-python">import json subject = { "name": "Biology", "teacher": {"name": "Nana Ama", "sex": "female"}, "students_size": 24, "elective": True, "lesson days": ["Tuesday", "Friday"], }</code>
在此代码中,indent 参数指定要使用多少个空格作为缩进,这使得输出更易于阅读。
json 模块默认只能处理简单的 Python 对象。对于像自定义类这样的复杂对象,您需要提供一个函数来告诉它如何序列化对象。这是一个例子:
<code class="language-json">{ "name": "Chinedu Obi", "age": 24, "country": "Nigeria", "languages": [ "Igbo", "English", "Yoruba" ], "marital status": "single", "employee": true, "experience": [ { "title": "Frontend Engineering Intern", "company": "Andela" }, { "title": "Frontend Engineer", "company": "Paystack" } ] }</code>
在此代码中,encode_person 函数用于将 Person 对象转换为可序列化格式。
如果您事先不知道 JSON 数据的结构,您仍然可以将其解析为 Python 对象并对其进行探索。这是一个例子:
<code class="language-python">import json with open('employee.json', 'r', encoding='utf-8') as file_object: employee_dict = json.load(file_object) print(employee_dict)</code>
在此代码中,json.loads() 将 JSON 字符串转换为 Python 字典,然后您可以对其进行迭代以探索其内容。
对于大型 JSON 文件,您可以使用 ijson 包,该包允许您流式传输 JSON 数据,而不是一次将所有数据都加载到内存中。这是一个例子:
<code>{'name': 'Chinedu Obi', 'age': 24, 'country': 'Nigeria', 'languages': ['Igbo', 'English', 'Yoruba'], 'marital status': 'single', 'employee': True, 'experience': [{'title': 'Frontend Engineering Intern', 'company': 'Andela'}, {'title': 'Frontend Engineer', 'company': 'Paystack'}]}</code>
在此代码中,ijson.items() 从 JSON 数据生成一个对象流,然后您可以对其进行迭代。
当 json 模块遇到无效的 JSON 时,它会引发 JSONDecodeError。您可以捕获此错误并适当地处理它。这是一个例子:
<code class="language-python">import json mother = { "name": "Asake Babatunde", "age": 28, "marital status": "Married", "children": ["Ayo", "Tolu", "Simi"], "staff": False, "next of kin": {"name": "Babatune Lanre", "relationship": "husband"}, } with open("mother.json", "w", encoding="utf-8") as file_handle: json.dump(mother, file_handle, indent=4)</code>
在此代码中,try/except 块捕获 JSONDecodeError 并打印错误消息。
requests 库使使用 JSON 数据发送 HTTP 请求和处理 JSON 响应变得容易。这是一个例子:
<code class="language-python">json.dump(obj, fp, indent)</code>
在此代码中,requests.post() 使用 JSON 数据发送 POST 请求,response.json() 解析 JSON 响应。
以上是在Python中使用JSON文件,并提供示例的详细内容。更多信息请关注PHP中文网其他相关文章!