7.4 KiB
Python 中的 JSON:如何读、写和解析
JSON 是 JavaScript 对象符号的缩写,是一个开放标准。尽管它的名字并不意味着如此,但它是一种独立于语言的数据格式。通过 Python 的 JSON 库,我们可以读取、写入和解析 JSON,以便使用这种通用的数据格式存储和交换数据。这是一种流行的数据格式,因为它对人类来说也很容易读写,尽管不像 YAML 那么容易!
在 Python 中使用 JSON 非常简单!Python 有两种数据类型,它们共同构成了在 Python 中使用 JSON 的完美工具:字典和列表。
目录
- 导入 JSON 库
- 如何在 Python 中解析 JSON
- 用 json.dumps 编码 JSON】
- 在命令行漂亮打印 JSON
- 如何在 python 中读取 JSON 文件
- 如何用 Python 把 JSON 写到文件里
- 常见问题解答
- 继续学习
导入 JSON 库
Python 附带了一个强大而优雅的 JSON 库来帮助你解码和编码 JSON。您可以通过以下方式导入模块:
import json
这个库是 Python 的一部分,所以你不需要用 Pip 包管理器安装它。
如何在 Python 中解析 JSON
解析一串 JSON 数据,也称为解码 JSON,就像使用json.loads(…)一样简单。Loads 是 load string 的缩写。
它转换:
这里有一个json.loads的例子:
https://crumb . sh/embed/xh 7 quabjqji
使用json.loads解析 JSON 字符串
如果上面的交互式示例不起作用(它仍处于测试阶段),这里有一个更静态的示例:
>>> 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 字典的页面上解释的那样。您可以自己检查:
>>> type(person)
<class 'dict'>
用 json.dumps 编码 JSON】
用 Python 的json.dumps对 JSON 数据进行编码就像解码一样简单。使用json.dumps(“转储到字符串”的缩写)将由字典、列表和其他本地类型组成的 Python 对象转换成一个字符串:
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. It's much appreciated and allows me to keep working on this site!
下面是同样的例子,以防上面的交互式例子在你的浏览器中不起作用:
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:
>>> person = {'name': 'erik', 'age': 38, 'married': True}
>>> print(json.dumps(person, indent=2))
{
"name": "erik",
"age": 38,
"married": true
}
在命令行漂亮打印 JSON
Python 的 JSON 模块也可以从命令行使用。它将验证和美化您的 JSON:
$ echo "{ \"name\": \"Monty\", \"age\": 45 }" | \
python3 -m json.tool
{
"name": "Monty",
"age": 45
}
不过,你也可能对使用 jq 工具感兴趣!
如何在 python 中读取 JSON 文件
除了json.loads,还有一个函数叫做json.load(不带 s)。它将从一个文件中加载数据,但是你必须自己打开文件。如果您想将 JSON 文件的内容读入 Python 并解析它,请使用以下示例:
with open('data.json') as json_file:
data = json.load(json_file)
...
如何用 Python 把 JSON 写到文件里
json.dump函数用于将数据写入 JSON 文件。你需要先用写模式打开文件:
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 的文章。
- JMESPath 是一种用于 JSON 的查询语言。Python 中的 JMESPath可以让你轻松地从 JSON 文档或字典中获取你需要的数据。
- 如果您需要在命令行上解析 JSON,请在一个名为 jq 的工具上尝试我们的文章!
- 复习一下使用 Python 打开、写入和读取文件的。