JMESPath 是一种 JSON 查询语言,允许你从 JSON 文档中提取和转换数据。按嵌套属性过滤是 JMESPath 的一个强大功能,可以让你查询复杂嵌套结构中的数据。
JMESPath 的嵌套属性过滤允许你:
要访问嵌套属性,可以使用点符号(.
)连接各级属性名:
parent.child.grandchild
对于数组中的嵌套对象,可以使用[]
符号:
array[].nestedProperty
{
"person": {
"name": "John",
"address": {
"city": "New York",
"zip": "10001"
}
}
}
查询城市:
person.address.city
结果:"New York"
{
"users": [
{
"id": 1,
"name": "Alice",
"preferences": {
"theme": "dark",
"notifications": true
}
},
{
"id": 2,
"name": "Bob",
"preferences": {
"theme": "light",
"notifications": false
}
}
]
}
查询所有使用深色主题的用户名:
users[?preferences.theme == 'dark'].name
结果:["Alice"]
{
"departments": [
{
"name": "Engineering",
"employees": [
{
"id": 101,
"name": "John",
"skills": ["Java", "Python"]
},
{
"id": 102,
"name": "Jane",
"skills": ["JavaScript", "React"]
}
]
},
{
"name": "Marketing",
"employees": [
{
"id": 201,
"name": "Mike",
"skills": ["SEO", "Content"]
}
]
}
]
}
查询所有掌握 JavaScript 技能的员工:
departments[].employees[?contains(skills, 'JavaScript')].name
结果:["Jane"]
{
"products": [
{
"id": 1,
"details": {
"color": "red"
}
},
{
"id": 2
}
]
}
查询有颜色属性的产品ID:
products[?contains(keys(@), 'details') && contains(keys(details), 'color')].id
结果:[1]
{
"orders": [
{
"orderId": "A123",
"customer": {
"id": "C001",
"tier": "gold"
},
"items": [
{
"productId": "P100",
"price": 99.99
}
]
},
{
"orderId": "A124",
"customer": {
"id": "C002",
"tier": "silver"
},
"items": [
{
"productId": "P101",
"price": 49.99
}
]
}
]
}
查询黄金会员且订单金额大于50的订单ID:
orders[?customer.tier == 'gold' && items[0].price > `50`].orderId
结果:["A123"]
解决方案:使用||
提供默认值
person.address.city || 'Unknown'
解决方案:使用[]
确保总是返回数组
departments[].employees[].name
解决方案:使用括号明确优先级
users[?(preferences.theme == 'dark' && preferences.notifications == `true`)].name
JMESPath的嵌套属性过滤功能特别适合处理现代Web应用和微服务架构中常见的复杂JSON数据结构。
没有搜到相关的文章