英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论