简体   繁体   English

jq查找其值为包含特定元素的数组的键

[英]jq find keys whose value is an array containing a specific element

the file is 文件是

{
    "ContentKey--4-0-47--Vovb1BQ": ["infra", "qa", "qa-ContentKey-4-0-47-Vovb1BQ", "internal-qa-Conten-WebServi-19E4PUWHRGD44-460820639.us-east-1.elb.amazonaws.com", "plan--default"],
    "ContentKey--4-0-47--zjOkiQ": ["svc", "dev", "dev-ContentKey-4-0-47-zjOkiQ", "dev-Conte-WebServi-KXJXZBDY113W-2116785917.us-east-1.elb.amazonaws.com", "plan--default"],
    "IdGenService--2001-4-22--CJUFaMQ": ["svc", "dev", "dev-IdGenService-2001-4-22-CJUFaMQ", "dev-IdGen-WebServi-R7RVXSYAV92W-304073075.us-east-1.elb.amazonaws.com"],
    "IdGenService--2001-4-22--Uhf9CTQ": ["svc", "qa", "qa-IdGenService-2001-4-22-Uhf9CTQ", "internal-qa-IdGenS-WebServi-RT5BI5EEVZP3-665537643.us-east-1.elb.amazonaws.com"]
}

I want to find the list of keys whose array value have the entry svc 我想找到其数组值具有条目svc的键列表

i could get the following to work 我可以得到以下工作

cat list.json | jq '. | map(select (. | contains(["svc"])))'

But the output is the value array and not the key itself 但输出是值数组而不是键本身

[
  [
    "svc",
    "dev",
    "dev-ContentKey-4-0-47-zjOkiQ",
    "dev-Conte-WebServi-KXJXZBDY113W-2116785917.us-east-1.elb.amazonaws.com",
    "plan--default"
  ],
  [
    "svc",
    "dev",
    "dev-IdGenService-2001-4-22-CJUFaMQ",
    "dev-IdGen-WebServi-R7RVXSYAV92W-304073075.us-east-1.elb.amazonaws.com"
  ],
  [
    "svc",
    "qa",
    "qa-IdGenService-2001-4-22-Uhf9CTQ",
    "internal-qa-IdGenS-WebServi-RT5BI5EEVZP3-665537643.us-east-1.elb.amazonaws.com"
  ]
]

The top-level object in your json is an object, not an array. json中的顶级对象是一个对象,而不是一个数组。 So .[] would only yield its values and discard the keys. 所以.[]只会产生它的值并丢弃键。 Use with_entries/1 to filter that object. 使用with_entries/1过滤该对象。 This converts an object to an array of key/value pairs and back with which you can apply filters to. 这会将对象转换为键/值对的数组,然后将其应用于过滤器。

$ jq --arg key 'svc' 'with_entries(select(any(.value[]; . == $key)))' list.json

Also, you should avoid using contains/1 here. 此外,您应该避免在这里使用contains/1 It's applied recursively so it will also match strings that contain the substring svc . 它是递归应用的,因此它也匹配包含子串svc的字符串。 ie, "Foosvcbar" will be matched. 即, "Foosvcbar"将匹配。

With your input, the following filter yields the output as shown: 根据您的输入,以下过滤器产生输出,如下所示:

to_entries[] | select( .value | index("svc") ) | .key

Output: 输出:

"ContentKey--4-0-47--zjOkiQ"
"IdGenService--2001-4-22--CJUFaMQ"
"IdGenService--2001-4-22--Uhf9CTQ"

In cases like this, using index/1 is both simpler and (potentially much) faster than using any/2 . 在这种情况下,使用index/1比使用any/2更简单且(可能更快)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM