如何在 Python 中解析 JSON
已发表: 2022-02-09JSON是一种流行的数据交换格式。 Python 附带一个内置的JSON模块来解析和处理 JSON 数据。 本教程将教您如何在 Python 中使用 JSON。
在本教程结束时,您将学会:
- JSON的基础知识,
- 如何在 Python 中解析和创建 JSON 字符串,以及
- 如何在 Python 中读取和写入 JSON 文件。
开始吧!
什么是 JSON?
JSON代表Java S cript Object Notation ,它是一种基于文本的数据交换格式。 尽管 JSON 最初是受到 JavaScript 对象的启发,但几乎所有的编程语言都支持使用 JSON。
如果您曾经使用过 API 或通读过配置文件,您可能会遇到 JSON。
查询 API 时以 JSON 格式发送和接收数据。 JSON 也广泛用于软件应用程序中的客户端-服务器通信。 此外,您还可以将 JSON 用于通用数据存储。
JSON 的格式与 Python 字典的格式非常相似。 字典是 Python 中强大的内置数据结构,可将数据存储在键值对中。
在我们进一步讨论之前,这里有几点值得注意:
- 在 Python 中,JSON 对象存储为字典。
- JSON 中的数组存储为 Python 列表。
- 在 JSON 中,布尔值表示为
true
和false
。 在 Python 中,这些被转换为布尔值True
和False
。
有关从 JSON 转换为 Python 的数据类型的更多详细信息,请阅读此处的文档。
由于json
模块是 Python 标准库的一部分,因此您不必安装它。 您可以导入到当前目录,如下所示:
import json
如何在 Python 中加载 JSON 字符串
在 Python 中加载 JSON 字符串的一般语法是:
<dict_obj> = json.loads(<json_str>)
这里,
-
<dict_obj>
是您要加载 JSON 字符串的 Python 字典, -
<json_str>
是任何有效的 JSON 字符串。
这会将<json_str>
加载到 Python 字典<dict_obj>
中。
让我们编写一个示例。 这里json_str
是一个 JSON 字符串。
json_str = ''' { "books": [ { "title": "The Wind in the Willows", "author": "Kenneth Grahame", "year": "1908" }, { "title": "To the Lighthouse", "author": "Virginia Woolf", "year": "1927" } ] } '''
下面的代码片段展示了如何使用loads()
方法将 JSON 字符串json_str
加载到 Python 字典中。 您可以使用内置的type()
函数来验证py_dict
是 Python 字典。
py_dict = json.loads(json_str) type(py_dict) # Output: dict print(py_dict) # Output {'books': [{'title': 'The Wind in the Willows', 'author': 'Kenneth Grahame', 'year': '1908'}, {'title': 'To the Lighthouse', 'author': 'Virginia Woolf', 'year': '1927'}]}
如上代码所示,JSON 字符串中的所有字段都是py_dict
中的键值对。
如何在 Python 中创建 JSON 字符串
假设您有一本 Python 字典。 那么如何从它创建一个 JSON 字符串呢?
您可以使用具有以下语法的dumps()
方法来执行此操作:
<json_str> = json.dumps(<dict_obj>)
这里,
-
<dict_obj>
是您要从中创建 JSON 字符串的 Python 字典, -
<json_str>
是生成的 JSON 字符串。
因此 dumps dumps()
方法将<dict_obj>
转储到 JSON 字符串<json_str>
中。
到我们现有的 Python 字典py_dict
。 让我们添加一个新键"movies"
。 您可以按照以下代码片段所示进行操作:
py_dict["movies"] = [{"title":"The Imitation Game","year":"2014", "lang":"en","watched":True}]
现在,让我们使用 dumps dumps()
方法将修改后的字典转储到新的 JSON 字符串json_str2
中。
json_str2 = json.dumps(py_dict) print(json_str2) # Output {"books": [{"title": "The Wind in the Willows", "author": "Kenneth Grahame", "year": "1908"}, {"title": "To the Lighthouse", "author": "Virginia Woolf", "year": "1927"}], "movies": [{"title": "The Imitation Game", "year": "2014", "lang": "en", "watched": true}]}
正如您在上面的示例中看到的,如果没有正确的格式,输出 JSON 字符串很难阅读。 您可以使用可选参数indent
来添加缩进。
您可以通过将indent
设置为像 2 这样的整数来做到这一点,如下所示:
json_str2 = json.dumps(py_dict, indent = 2) print(json_str2) # Output { "books": [ { "title": "The Wind in the Willows", "author": "Kenneth Grahame", "year": "1908" }, { "title": "To the Lighthouse", "author": "Virginia Woolf", "year": "1927" } ], "movies": [ { "title": "The Imitation Game", "year": "2014", "lang": "en", "watched": true } ] }
观察输出是如何用缩进格式化的,很容易理解。

注意:如果您希望键按字母顺序排序,可以将
sort_keys
参数设置为True
。
正如您在下面的代码片段中看到的那样,键现在已按字母顺序排序。
json_str2 = json.dumps(py_dict, indent = 2, sort_keys=True) print(json_str2) # Output { "books": [ { "author": "Kenneth Grahame", "title": "The Wind in the Willows", "year": "1908" }, { "author": "Virginia Woolf", "title": "To the Lighthouse", "year": "1927" } ], "movies": [ { "lang": "en", "title": "The Imitation Game", "watched": true, "year": "2014" } ]
键现在按字母顺序显示: "author"
、 "title"
和"year"
。
到目前为止,您已经学习了如何在 Python 中使用 JSON 字符串。 在下一部分中,您将学习如何使用 JSON 文件。
如何在 Python 中读取 JSON 文件
要在 Python 中读取 JSON 文件,请使用以下语法:
json.load(<json-file>) # where <json-file> is any valid JSON file.
注意我们如何使用
load()
方法而不是loads()
方法。loads()
加载一个JSON 字符串,而load()
加载一个JSON 文件。
在 Python 中处理文件时,您应该考虑使用上下文管理器。 您也可以尝试如下读取文件,而不使用上下文管理器:
my_file = open('students.json','r') contents = my_file.read() print(contents) file.close()
如果您不关闭文件,则可能会浪费资源。
但是,在使用上下文管理器时,一旦文件操作完成,文件就会自动关闭。
并且可以使用上下文管理器来读取文件,如下图:
with open('students.json','r') as file: data = json.load(file) print(data) # Output {'students': [{'roll_num': 'cs27', 'name': 'Anna', 'course': 'CS'}, {'roll_num': 'ep30', 'name': 'Kate', 'course': 'PHY'}]}
当您从文件中读取时,将模式指定为已读——在上面的代码中用'r'
表示。
注意:为了轻松浏览当前目录,请确保 JSON 文件与
main.py
位于同一文件夹中,如下图所示。 如果您的 JSON 文件位于不同的文件夹中,请务必指定文件的路径。

在下一部分中,您将学习如何写入 JSON 文件。
如何在 Python 中写入 JSON 文件
要写入现有 JSON 文件或创建新 JSON 文件,请使用如下所示的dump()
方法:
json.dump(<dict_obj>,<json_file>) # where <dict_obj> is a Python dictionary # and <json_file> is the JSON file
所以上面的语法将字典<dict_obj>
转储到 JSON 文件<json_file>
中。
在上一节中,我们有字典py_dict
。 现在让我们将其转储到一个新的 JSON 文件中。 让我们将其命名为new_file.json
。
以下代码单元显示了如何使用dump()
函数:
with open('new_file.json','w') as file: json.dump(py_dict,file)
注意:如果文件存在,以写入模式 (
w
) 打开文件会覆盖内容。 如果该文件不存在,则创建该文件。
执行上述代码单元后,您会看到在当前工作目录中创建了一个新的 JSON 文件。 您可以继续检查 JSON 文件的内容。

写入文件时,关键目标是数据存储。 如果您想保留格式,还可以使用indent
和sort_keys
参数。
结论
是时候快速总结一下了。
在本教程中,您学习了:
- 使用 JSON 的基础知识,
- 如何使用
loads()
和load()
方法分别读取 JSON 字符串和 JSON 文件, - 如何使用
dumps()
和dump()
方法将 Python 字典分别转储为 JSON 字符串和 JSON 文件。
我希望您发现本教程对您有所帮助。 快乐学习!
您还可以查看用于解析、格式化和验证的 JSON 工具。