geekdoc-python-zh/docs/pythonland/55.md

169 lines
7.4 KiB
Markdown
Raw Permalink Normal View History

2024-03-03 22:54:39 +08:00
# Python 中的 JSON:如何读、写和解析
> 原文:[https://python.land/data-processing/working-with-json](https://python.land/data-processing/working-with-json)
JSON 是 **JavaScript 对象符号**的缩写,是一个开放标准。尽管它的名字并不意味着如此,但它是一种独立于语言的数据格式。通过 Python 的 JSON 库,我们可以读取、写入和解析 JSON以便使用这种通用的数据格式存储和交换数据。这是一种流行的数据格式因为它对人类来说也很容易读写尽管不像 [YAML](https://python.land/data-processing/python-yaml) 那么容易!
在 Python 中使用 JSON 非常简单Python 有两种数据类型,它们共同构成了在 Python 中使用 JSON 的完美工具:[字典](https://python.land/python-datatypes/dictionaries)和[列表](https://python.land/python-data-types/python-list)。
目录
* [导入 JSON 库](#Importing_the_JSON_library "Importing the JSON library")
* [如何在 Python 中解析 JSON](#How_to_parse_JSON_in_Python "How to parse JSON in Python")
* [用 json.dumps 编码 JSON】](#Encoding_JSON_with_jsondumps "Encoding JSON with json.dumps")
* [在命令行漂亮打印 JSON](#Pretty_printing_JSON_on_the_command_line "Pretty printing JSON on the command line")
* [如何在 python 中读取 JSON 文件](#How_to_read_a_JSON_file_in_python "How to read a JSON file in python")
* [如何用 Python 把 JSON 写到文件里](#How_to_write_JSON_to_a_file_in_Python "How to write JSON to a file in Python")
* [常见问题解答](#Frequently_Asked_Questions "Frequently Asked Questions")
* [继续学习](#Keep_learning "Keep learning")
## 导入 JSON 库
Python 附带了一个强大而优雅的 [JSON 库](https://docs.python.org/3/library/json.html)来帮助你解码和编码 JSON。您可以[通过以下方式导入模块](https://python.land/project-structure/python-modules):
```py
import json
```
这个库是 Python 的一部分,所以你不需要用 [Pip 包管理器](https://python.land/virtual-environments/installing-packages-with-pip)安装它。
## 如何在 Python 中解析 JSON
解析一串 JSON 数据,也称为解码 JSON就像使用`json.loads(…)`一样简单。Loads 是 load string 的缩写。
它转换:
* [字典的对象](https://python.land/python-datatypes/dictionaries)
* 数组到列表,
* [布尔值](https://python.land/introduction-to-python/booleans-and-conditionals)、[整数](https://python.land/python-datatypes/python-integer)、浮点数和[字符串](https://python.land/introduction-to-python/strings)被识别出来,并将被转换成 Python 中的正确类型
* 任何`null`都将被转换成 Python 的`None`类型
这里有一个`json.loads`的例子:
[https://crumb . sh/embed/xh 7 quabjqji](https://crumb.sh/embed/xH7QUABJqji)
使用`json.loads`解析 JSON 字符串
如果上面的交互式示例不起作用(它仍处于测试阶段),这里有一个更静态的示例:
```py
>>> import json
>>> jsonstring = '{"name": "erik", "age": 38, "married": true}'
>>> person = json.loads(jsonstring)
>>> print(person['name'], 'is', person['age'], 'years old')
erik is 38 years old
>>> print(person)
{'name': 'erik', 'age': 38, 'married': True}
```
输出可能看起来像一个字符串,但它实际上是一个字典,你可以在你的代码中使用,就像我们关于 [Python 字典](https://python.land/python-datatypes/dictionaries)的页面上解释的那样。您可以自己检查:
```py
>>> type(person)
<class 'dict'>
```
## 用 json.dumps 编码 JSON】
用 Python 的`json.dumps`对 JSON 数据进行编码就像解码一样简单。使用`json.dumps`(“转储到字符串”的缩写)将由[字典](https://python.land/python-data-types/dictionaries)、[列表](https://python.land/python-data-types/python-list)和其他本地类型组成的 Python 对象转换成一个字符串:
[https://crumb.sh/embed/JdYSfwepFSH](https://crumb.sh/embed/JdYSfwepFSH)
将字典编码成 JSON 字符串
Thank you for reading my tutorials. I write these in my free time, and it requires a lot of time and effort. I use ads to keep writing these *free* articles, I hope you understand! **Support me by disabling your adblocker on my website** or, alternatively, **[buy me some coffee](https://www.buymeacoffee.com/pythonland)**. It's much appreciated and allows me to keep working on this site!
下面是同样的例子,以防上面的交互式例子在你的浏览器中不起作用:
```py
import json
person = {'name': 'erik', 'age': 38, 'married': True}
json_string = json.dumps(person)
print(json_string)
# {"name": "erik", "age": 38, "married": true}
# To make sure, let's print the type too
print(type(json_string))
# <class 'str'>
```
这是同一个文档,转换回字符串!如果想让 JSON 文档更易于阅读,可以使用 indent 选项。它将使用空格字符很好地格式化 JSON:
```py
>>> person = {'name': 'erik', 'age': 38, 'married': True}
>>> print(json.dumps(person, indent=2))
{
"name": "erik",
"age": 38,
"married": true
}
```
## 在命令行漂亮打印 JSON
Python 的 JSON 模块也可以从命令行使用。它将验证和美化您的 JSON:
```py
$ echo "{ \"name\": \"Monty\", \"age\": 45 }" | \
python3 -m json.tool
{
"name": "Monty",
"age": 45
}
```
不过,你也可能对使用 [jq 工具](https://python.land/the-unix-shell/process-json-with-jq)感兴趣!
## 如何在 python 中读取 JSON 文件
除了`json.loads`,还有一个函数叫做`json.load`(不带 s)。它将从一个文件中加载数据,但是你必须[自己打开文件](https://python.land/operating-system/python-files#Open_a_file_in_Python)。如果您想将 JSON 文件的内容读入 Python 并解析它,请使用以下示例:
```py
with open('data.json') as json_file:
data = json.load(json_file)
...
```
## 如何用 Python 把 JSON 写到文件里
`json.dump`函数用于将数据写入 JSON 文件。你需要先用写模式打开文件:
```py
data = {'name': 'Eric', 'age': 38 }
with open('data.json', 'w') as json_file:
json.dump(data, json_file)
```
## 常见问题解答
**How do I convert a list (array) to JSON in Python?**
简单地使用上面描述的方法。`json.dump`和`json.dumps`函数接受字典和列表
**How do I convert a dict or dictionary to JSON in Python?**
类似于数组,所以在字典上使用`json.dump` 或`json.dumps`。
**How can I sort the JSON output in Python?**
dump 和 dumps 函数都接受一个叫做 sort_keys 的选项,例如:`json.dumps(data, sort_keys=True)`。
**Does the JSON library output Unicode data?**
默认情况下:否。库输出 ASCII 并将转换不属于 ASCII 的字符。如果希望输出 Unicode请将 ensure _ ascii 设置为 False。示例:`json.dumps(data, ensure_ascii=False)`
## 继续学习
* 如果你正在寻找一种易于人类编写的格式(例如:配置文件),请阅读我们关于用 Python 读写 [YAML 的文章。](https://python.land/data-processing/python-yaml)
* JMESPath 是一种用于 JSON 的查询语言。[Python 中的 JMESPath](https://python.land/data-processing/working-with-json/jmespath)可以让你轻松地从 JSON 文档或字典中获取你需要的数据。
* 如果您需要在命令行上解析 JSON请在一个名为 jq 的工具上尝试我们的文章!
* 复习一下使用 Python 打开、写入和读取文件的[。](https://python.land/operating-system/python-files)