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

102 lines
3.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# JMS path Python:JSON 查询语言
> 原文:[https://python . land/data-processing/working-with-JSON/jmespath](https://python.land/data-processing/working-with-json/jmespath)
JMESPath 是一种 JSON 查询语言。Python 中的 JMESPath 允许您轻松地从 JSON 文档或字典中获取所需的数据。这个库可用于 Python也可用于许多其他编程语言这意味着如果您掌握了 JMESPath 查询语言,您可以在许多地方使用它。
目录
* [JMS path 解决的问题](#The_problem_JMESPath_solves "The problem JMESPath solves")
* [为 Python 安装 JMESPath】](#Installing_JMESPath_for_Python "Installing JMESPath for Python")
* [JMESPath Python 示例](#JMESPath_Python_examples "JMESPath Python examples")
* [继续学习](#Keep_learning "Keep learning")
## JMS path 解决的问题
正如我们在上一页看到的,使用 [Python 自己的 JSON 库](https://python.land/data-processing/working-with-json),很容易从 Python 字典中获得嵌套值。例如:`doc["person"]["age"]`将在如下所示的文档中获取年龄的嵌套值:
```py
{
"persons": {
"name": "erik",
"age": "38"
}
}
```
但是,如果您想从一个人员数组中提取所有的年龄字段,该怎么办呢?
```py
{
"persons": [
{ "name": "erik", "age": 38 },
{ "name": "john", "age": 45 },
{ "name": "rob", "age": 14 }
]
}
```
我们可以编写一个 [Python for-loop](https://python.land/introduction-to-python/python-for-loop) 并遍历所有人。很简单。但是循环很慢,并且会给代码带来复杂性。这就是**JMS path**的用武之地!
## 为 Python 安装 JMESPath】
JMESPath 不是 Python 标准库的一部分,这意味着您需要用 [pip](https://python.land/virtual-environments/installing-packages-with-pip) 或 [pipenv](https://python.land/virtual-environments/pipenv) 来安装它。与大多数 Python 包一样JMESPath 包[托管在 PyPI](https://pypi.org/project/jmespath/) 上。它的名字并不奇怪,就是 jmespath。
例如,在[虚拟环境](https://python.land/virtual-environments/virtualenv)中使用 pip 时,可以[安装 pip](https://python.land/virtual-environments/installing-packages-with-pip) [导入模块](https://python.land/project-structure/python-modules),如下:
```py
$ pip3 install jmespath
$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
>>> import jmespath
>>> j = { "people": [{ "name": "erik", "age": 38 }] }
>>> jmespath.search("people[*].age", j)
[38]
>>>
```
## JMESPath Python 示例
让我们从一些简单的用例开始。我们将从数组中获取第一个人,然后获取第一个人的年龄:
```py
>>> jmespath.search('persons[0]', persons)
{'name': 'erik', 'age': 38}
>>> jmespath.search('persons[0].age', persons)
38
```
在上面的问题陈述中,我们希望从 JSON 文档中的人员数组中提取所有年龄字段。这个 JMESPath 表达式将完成这项工作:
```py
>>> import jmespath
>>> persons = {
... "persons": [
... { "name": "erik", "age": 38 },
... { "name": "john", "age": 45 },
... { "name": "rob", "age": 14 }
... ]
... }
>>> jmespath.search('persons[*].age', persons)
[38, 45, 14]
```
假设您想过滤列表只获取名为“erik”的人的年龄。您可以使用过滤器来完成此操作:
```py
>>> jmespath.search("persons[?name=='erik'].age", persons)
[38]
```
注意,我们现在使用双引号,因为我们需要在过滤器表达式中引用名称。
## 继续学习
你现在可以开始实验了!如果您想了解更多信息,请尝试以下链接:
* [互动教程](https://jmespath.org/tutorial.html)
* JMESPath 站点上的[示例](https://jmespath.org/examples.html)