英文:
Select an object based on the value of another object in jq
问题
The logic to find the build number of the last branch that was built can be combined in one jq command as follows:
jq '.buildsByBranchName[.lastBuiltRevision.branch[0].name].buildNumber'
This command first accesses the branch name with .lastBuiltRevision.branch[0].name
, which is origin/master
, and then uses it to access the corresponding build number in .buildsByBranchName
, giving you the desired result: 28694
.
英文:
Given the following (simplified) JSON.
{
"buildsByBranchName": {
"origin/master": { "buildNumber": 28694 },
"master": { "buildNumber": 28563 },
"refs/remotes/origin/master": { "buildNumber": 4094 }
},
"lastBuiltRevision": {
"branch": [
{ "name": "origin/master" }
]
}
}
I want to find the build number of the last branch that was built.
The logic to do so is to find the name of the branch .lastBuiltRevision.branch[0].name
= origin/master
. Then use the branch name to find the build number .buildsByBranchName | to_entries[] | select(."key" == "origin/master") .value.buildNumber
= 28694
. But I don't know how to combine them.
After .buildsByBranchName
I have no access to lastBuiltRevision
in my select. Or is there any way?
I can probably do this with two calls to jq. But I'd really like to do this with only one.
答案1
得分: 3
不需要使用 select()
,您可以将分支作为 buildByBranchName
中所需的键使用:
.buildsByBranchName[.lastBuiltRevision.branch[0].name].buildNumber
输出:28694
如果您需要在更多地方使用 .lastBuiltRevision.branch[0].name
,考虑设置一个变量:
.lastBuiltRevision.branch[0].name as $branch | .buildsByBranchName[$branch].buildNumber
英文:
There's no need for select()
, you can use the branch as the desired key in buildByBranchName
:
.buildsByBranchName[.lastBuiltRevision.branch[0].name].buildNumber
Output: 28694
Should you need to use the .lastBuiltRevision.branch[0].name
on more places, consider setting a variable:
.lastBuiltRevision.branch[0].name as $branch | .buildsByBranchName[$branch].buildNumber
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论