简体   繁体   English

使用 jq 模式匹配字段名称

[英]Pattern matching field names with jq

This is a very basic (probably silly) question but I can't get it to work...这是一个非常基本的(可能是愚蠢的)问题,但我无法让它起作用......

I have a JSON file with this structure:我有一个具有以下结构的 JSON 文件:

{
    "data": {
        "what a burger": [1,2,3],
        "wap": [66],
        "the map": [11,20],
        "H. Incandenza": [1,1],
        "What a burger": [a,a,3]
    }
}

I would like to extract the values of the fields within data whose "name" matches a certain pattern.我想提取“名称”与特定模式匹配的数据中字段的值。 For example, I would like to extract all the case-insensitive coincidences of "what a burger" to get例如,我想提取“what a burger”的所有不区分大小写的巧合来获得

[1,2,3],[a,a,3]

My guess would be something like我的猜测是这样的

jq '.data | match("what a burger";"i")'

but this results in但这导致

jq: error (at <stdin>:9): object ({"what a bu...) cannot be matched, as it is not a string

Cheers.干杯。

Your statement does not work, because you try to feed the data object into match, but match can only work on strings.您的语句不起作用,因为您尝试将数据对象提供给 match,但 match 只能处理字符串。

The following expression will do what you want.以下表达式将执行您想要的操作。 The to_entries converts the object to an array of keys and values. to_entries将对象转换为键和值的数组。 Then we iterate over this array by using map and select all entries where the .key (now a string) has a match .然后我们使用map遍历这个数组,并select .key (现在是一个字符串) match所有条目。 Finally we just print out the value of every element.最后我们只是打印出每个元素的值。

.data | to_entries | map(select(.key | match("what a burger";"i"))) | map(.value)

However, two comments:但是,有两点评论:

  • The [a,a,3] is not allowed in JSON, because a is not a number. JSON 中不允许使用[a,a,3] ,因为a不是数字。
  • It works because the keys ARE actually different, even if only the letter case is not equal.它起作用是因为键实际上是不同的,即使只有字母大小写不相等。 If at least two keys are identical, you will run into problems, because keys should be unique.如果至少有两个键相同,则会遇到问题,因为键应该是唯一的。 In fact, jq will only output one of the elements then.事实上, jq只会输出其中一个元素。

Here's a slightly briefer alternative:这是一个稍微简短的替代方案:

.data | with_entries(select(.key|match("what a burger";"i")))[]

After rectifying the input, and using jq's -c option, this would produce the two lines:纠正输入后,并使用 jq 的 -c 选项,这将产生两行:

[1,2,3]
["a","a",3]

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

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