提取与模式匹配的其他值的值。

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

jq : extract value where other value matches pattern

问题

I have the following JSON:

{
  "id": "jboss_data1",
  "DS1": {
    "policy_name": "CAT_LOCATION",
    "username": "PRODUCTION_1",
    "password_clear": "7bla1234"
  },
  "DS3": {
    "policy_name": "CAT_SRC",
    "username": "PRODUCTION_2",
    "password_clear": "foo7864"
  },
  "DS4": {
    "policy_name": "CAT_FOLDER",
    "username": "PRODUCTION_3",
    "password_clear": "123bar456"
  }
}

In bash, I'm trying to extract the password_clear value when the username matches my variable.

I've tried something like:

jq -r --arg user "${user_picked}" '.[] | select(.username == $user).password_clear' file.json

Could you please guide me to the correct syntax for this request?

英文:

I have the following json :

{
  "id": "jboss_data1",
  "DS1": {
    "policy_name": "CAT_LOCATION",
    "username": "PRODUCTION_1",
    "password_clear": "7bla1234",
  },
  "DS3": {
    "policy_name": "CAT_SRC",
    "username": "PRODUCTION_2",
    "password_clear": "foo7864",
  },
  "DS4": {
    "policy_name": "CAT_FOLDER",
    "username": "PRODUCTION_3",
    "password_clear": "123bar456",
  }
}

In bash, I'm trying to extract the password_clear value when the username matches my variable.

I've tried something like

jq -r --arg user "${user_picked}" '.[]|select(.value.username=="$user").password_clear' file.json

(I've also tried a lot of different other combinations, but without success...)

Could you please guide me to the correct syntax for this request ?

Regards

答案1

得分: 4

Here's the translated content:

自从不是所有对象都有username字段,你需要使用可选对象标识符-索引?)如.username?来捕捉那些缺失的对象:

jq -r --arg user "PRODUCTION_1" \
  '.[] | select(.username? == $user).password_clear' file.json

输出:

7bla1234

关于你的尝试,你使用了.value,但这并不需要,因为.[]可以很好地循环遍历对象。

.value可以来自于to_entries,将对象转换为键/值对,但再次使用.[]更简单。

英文:

Since not all objects have the username field, you'll need to use the Optional Object Identifier-Index (?) as .username? to catch those missing ones:

jq -r --arg user "PRODUCTION_1" \
  '.[] | select(.username? == $user).password_clear' file.json

Output:

7bla1234

Regarding your attempt, you were using .value, but that's not needed since .[] can loop over objects just fine.

The .value could come from to_entries, to convert the object to key/value pair, but again, using .[] is a lot easier.

huangapple
  • 本文由 发表于 2023年6月29日 18:05:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580033.html
匿名

发表评论

匿名网友

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

确定