根据jq中另一个对象的值选择一个对象。

huangapple go评论52阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月8日 22:32:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定