使用 jq,如何根据键限制值
Using jq, how can I limit values based on a key
对于如下所示的输入文件:
{
"employees": [
{
"number": "101",
"tags": [
{
"value": "yes",
"key": "management"
},
{
"value": "joe",
"key": "login"
},
{
"value": "joe blogs",
"key": "name"
}
]
},
{
"number": "102",
"tags": [
{
"value": "no",
"key": "management"
},
{
"value": "jane",
"key": "login"
},
{
"value": "jane doe",
"key": "name"
}
]
},
{
"number": "103",
"tags": [
{
"value": "no",
"key": "management"
},
{
"value": "john",
"key": "login"
},
{
"value": "john doe",
"key": "name"
}
]
}
]
}
...我想获取所有非管理人员的详细信息,以便所需的输出如下所示:
{
"number": "102",
"name": "jane doe",
"login": "jane"
}
{
"number": "103",
"name": "john doe",
"login": "john"
}
我不知道如何在不选择该键的情况下根据该键限制结果(在本例中 "management")
使用 from_entries
,这对我有用:
$ jq '.employees[] | {number: .number, tags: .tags | from_entries} | select(.tags.management=="no") | {number: .number, name: .tags.name, login: .tags.login}' input
... 输出为:
{
"number": "102",
"name": "jane blogs",
"login": "jane"
}
{
"number": "103",
"name": "john doe",
"login": "john"
}
可能有更好的方法来实现我想要的,所以如果有人想提供更好的解决方案,我会暂时搁置这个问题。
下面是一个稍微简洁的解决方案:
.employees[]
| .tags |= from_entries
| select(.tags.management == "no")
| {number, "name": .tags.name, "login": .tags.login}
这是另一个使用 from_entries
的解决方案
.employees[]
| {number} + (.tags | from_entries)
| if .management == "no" then {number, name, login} else empty end
对于如下所示的输入文件:
{
"employees": [
{
"number": "101",
"tags": [
{
"value": "yes",
"key": "management"
},
{
"value": "joe",
"key": "login"
},
{
"value": "joe blogs",
"key": "name"
}
]
},
{
"number": "102",
"tags": [
{
"value": "no",
"key": "management"
},
{
"value": "jane",
"key": "login"
},
{
"value": "jane doe",
"key": "name"
}
]
},
{
"number": "103",
"tags": [
{
"value": "no",
"key": "management"
},
{
"value": "john",
"key": "login"
},
{
"value": "john doe",
"key": "name"
}
]
}
]
}
...我想获取所有非管理人员的详细信息,以便所需的输出如下所示:
{
"number": "102",
"name": "jane doe",
"login": "jane"
}
{
"number": "103",
"name": "john doe",
"login": "john"
}
我不知道如何在不选择该键的情况下根据该键限制结果(在本例中 "management")
使用 from_entries
,这对我有用:
$ jq '.employees[] | {number: .number, tags: .tags | from_entries} | select(.tags.management=="no") | {number: .number, name: .tags.name, login: .tags.login}' input
... 输出为:
{
"number": "102",
"name": "jane blogs",
"login": "jane"
}
{
"number": "103",
"name": "john doe",
"login": "john"
}
可能有更好的方法来实现我想要的,所以如果有人想提供更好的解决方案,我会暂时搁置这个问题。
下面是一个稍微简洁的解决方案:
.employees[]
| .tags |= from_entries
| select(.tags.management == "no")
| {number, "name": .tags.name, "login": .tags.login}
这是另一个使用 from_entries
的解决方案 .employees[]
| {number} + (.tags | from_entries)
| if .management == "no" then {number, name, login} else empty end