Skip to content

使用 JMESPath 查询 JSON#

¥Query JSON with JMESPath

JMESPath 是一种 JSON 查询语言,可用于从 JSON 文档中提取和转换元素。有关如何使用 JMESPath 的完整详细信息,请参阅 JMESPath 文档

¥JMESPath is a query language for JSON that you can use to extract and transform elements from a JSON document. For full details of how to use JMESPath, refer to the JMESPath documentation.

jmespath() 方法#

¥The jmespath() method

n8n 提供了一个自定义方法 jmespath()。使用此方法使用 JMESPath 查询语言搜索 JSON 对象。

¥n8n provides a custom method, jmespath(). Use this method to perform a search on a JSON object using the JMESPath query language.

基本语法为:

¥The basic syntax is:

1
$jmespath(object, searchString)
1
_jmespath(object, searchString)

为了帮助你理解该方法的作用,以下是等效的更长的 JavaScript 代码:

¥To help understand what the method does, here is the equivalent longer JavaScript:

1
2
var jmespath = require('jmespath');
jmespath.search(object, searchString);

Expressions must be single-line

较长的代码示例在表达式中无法运行,因为表达式必须是单行的。

¥The longer code example doesn't work in Expressions, as they must be single-line.

object 是一个 JSON 对象,例如前一个节点的输出。searchString 是用 JMESPath 查询语言编写的表达式。JMESPath 规范 提供了一个受支持表达式的列表,而 教程示例 则提供了交互式示例。

¥object is a JSON object, such as the output of a previous node. searchString is an expression written in the JMESPath query language. The JMESPath Specification provides a list of supported expressions, while their Tutorial and Examples provide interactive examples.

Search parameter order

JMESPath 规范 中的示例遵循 search(searchString, object) 的模式。n8n 使用的 JMESPath JavaScript 库 支持 search(object, searchString)。这意味着在使用 JMESPath 文档中的示例时,你可能需要更改搜索函数参数的顺序。

¥The examples in the JMESPath Specification follow the pattern search(searchString, object). The JMESPath JavaScript library, which n8n uses, supports search(object, searchString) instead. This means that when using examples from the JMESPath documentation, you may need to change the order of the search function parameters.

常见任务#

¥Common tasks

本节提供了一些常见操作的示例。更多示例和详细指南,请参阅 JMESPath 官方文档

¥This section provides examples for some common operations. More examples, and detailed guidance, are available in JMESPath's own documentation.

尝试这些示例时,你需要将代码节点模式设置为“每个项目运行一次”。

¥When trying out these examples, you need to set the Code node Mode to Run Once for Each Item.

将 JMESPath 表达式应用于带有投影的元素集合#

¥Apply a JMESPath expression to a collection of elements with projections

JMESPath 投影文档 事件获取:

¥From the JMESPath projections documentation:

投影是 JMESPath 的关键特性之一。使用它将表达式应用于元素集合。JMESPath 支持五种投影格式:

¥Projections are one of the key features of JMESPath. Use it to apply an expression to a collection of elements. JMESPath supports five kinds of projections:

  • 列表投影

¥List Projections * 切片投影

¥Slice Projections * 对象投影

¥Object Projections * 展平投影

¥Flatten Projections * 按投影筛选

¥Filter Projections

以下示例展示了列表、切片和对象投影的基本用法。请参阅 JMESPath 投影文档,了解每种投影类型的详细说明以及更多示例。

¥The following example shows basic usage of list, slice, and object projections. Refer to the JMESPath projections documentation for detailed explanations of each projection type, and more examples.

给定来自 webhook 节点的以下 JSON:

¥Given this JSON from a webhook node:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[
  {
    "headers": {
      "host": "n8n.instance.address",
      ...
    },
    "params": {},
    "query": {},
    "body": {
      "people": [
        {
          "first": "James",
          "last": "Green"
        },
        {
          "first": "Jacob",
          "last": "Jones"
        },
        {
          "first": "Jayden",
          "last": "Smith"
        }
      ],
      "dogs": {
        "Fido": {
          "color": "brown",
          "age": 7
        },
        "Spot": {
          "color": "black and white",
          "age": 5
        }
      }
    }
  }
]

检索所有人物名字的 list 格式列表:

¥Retrieve a list of all the people's first names:

1
2
3
4
```js
{{$jmespath($json.body.people, "[*].first" )}}
// Returns ["James", "Jacob", "Jayden"]
```
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
```js
let firstNames = $jmespath($json.body.people, "[*].first" )
return {firstNames};
/* Returns:
[
	{
		"firstNames": [
			"James",
			"Jacob",
			"Jayden"
		]
	}
]
*/
```
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
firstNames = _jmespath(_json.body.people, "[*].first" )
return {"firstNames":firstNames}
"""
Returns:
[
 	{
		"firstNames": [
			"James",
			"Jacob",
			"Jayden"
		]
	}
]
"""

获取用户名字的 slice 索引

¥Get a slice of the first names:

1
2
3
4
```js
{{$jmespath($json.body.people, "[:2].first")}}
// Returns ["James", "Jacob"]
```
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let firstTwoNames = $jmespath($json.body.people, "[:2].first");
return {firstTwoNames};
/* Returns:
[
	{
		"firstNames": [
			"James",
			"Jacob",
			"Jayden"
		]
	}
]
*/
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
firstTwoNames = _jmespath(_json.body.people, "[:2].first" )
return {"firstTwoNames":firstTwoNames}
"""
Returns:
[
	{
		"firstTwoNames": [
		"James",
		"Jacob"
		]
	}
]
"""

使用 对象投影 获取狗狗的年龄列表:

¥Get a list of the dogs' ages using object projections:

1
2
3
4
```js
{{$jmespath($json.body.dogs, "*.age")}}
// Returns [7,5]
```
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let dogsAges = $jmespath($json.body.dogs, "*.age");
return {dogsAges};
/* Returns:
[
	{
		"dogsAges": [
			7,
			5
		]
	}
]
*/
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
dogsAges = _jmespath(_json.body.dogs, "*.age")
return {"dogsAges": dogsAges}
"""
Returns:
[
	{
		"dogsAges": [
			7,
			5
		]
	}
]
"""

选择多个元素并创建新列表或对象#

¥Select multiple elements and create a new list or object

使用 多选 从 JSON 对象中选择元素并将它们组合成新的列表或对象。

¥Use Multiselect to select elements from a JSON object and combine them into a new list or object.

给定来自 webhook 节点的以下 JSON:

¥Given this JSON from a webhook node:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[
  {
    "headers": {
      "host": "n8n.instance.address",
      ...
    },
    "params": {},
    "query": {},
    "body": {
      "people": [
        {
          "first": "James",
          "last": "Green"
        },
        {
          "first": "Jacob",
          "last": "Jones"
        },
        {
          "first": "Jayden",
          "last": "Smith"
        }
      ],
      "dogs": {
        "Fido": {
          "color": "brown",
          "age": 7
        },
        "Spot": {
          "color": "black and white",
          "age": 5
        }
      }
    }
  }
]

使用多选列表获取名字和姓氏,并创建包含这两个名字的新列表:

¥Use multiselect list to get the first and last names and create new lists containing both names:

1
2
3
4
```js
{{$jmespath($json.body.people, "[].[first, last]")}}
// Returns [["James","Green"],["Jacob","Jones"],["Jayden","Smith"]]
```
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
```js
let newList = $jmespath($json.body.people, "[].[first, last]");
return {newList};
/* Returns:
[
	{
		"newList": [
			[
				"James",
				"Green"
			],
			[
				"Jacob",
				"Jones"
			],
			[
				"Jayden",
				"Smith"
			]
		]
	}
]
*/
```
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
newList = _jmespath(_json.body.people, "[].[first, last]")
return {"newList":newList}
"""
Returns:
[
	{
		"newList": [
			[
				"James",
				"Green"
			],
			[
				"Jacob",
				"Jones"
			],
			[
				"Jayden",
				"Smith"
			]
		]
	}
]
"""

箭头函数的替代方案表达式#

¥An alternative to arrow functions in expressions

例如,通过从代码节点返回以下代码来生成一些输入数据:

¥For example, generate some input data by returning the below code from the Code node:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
return[
  {
    "json": {      
      "num_categories": "0",
      "num_products": "45",
      "category_id": 5529735,
      "parent_id": 1407340,
      "pos_enabled": 1,
      "pos_favorite": 0,
      "name": "HP",
      "description": "",
      "image": ""
    }
  },
  {
    "json": {
      "num_categories": "0",
      "num_products": "86",
      "category_id": 5529740,
      "parent_id": 1407340,
      "pos_enabled": 1,
      "pos_favorite": 0,
      "name": "Lenovo",
      "description": "",
      "image": ""
    }
  }  
]

可以进行类似 "查找名称为 Lenovo 的项目,并告诉我其类别 ID。" 的搜索。

¥You could do a search like "find the item with the name Lenovo and tell me their category ID."

{{ $jmespath($("Code").all(), "[?json.name=='Lenovo'].json.category_id") }}