Pattern Match Field Names with jq

This is a very simple (maybe stupid) question, but I can't get it to work ...

I have a json file with this structure

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

and I would like to extract the values ​​of the fields inside the data whose "name" matches a specific pattern. For example, I would like to extract all the case insensitive matches “what is a hamburger” to get

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

My guess would be like

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

but it leads to

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

Greetings.

+5
source share
2 answers

Your expression does not work because you are trying to pass a data object into a match, but a match can only work with strings.

The following expression will do what you want. to_entries converts an object into an array of keys and values. Then we iterate over this array with map and select all entries in which .key (now a string) has match . Finally, we simply print out the value of each element.

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

However, two comments:

  • JSON does not allow [a,a,3] because a not a number.
  • This works because the ARE keys are really different, even if the case with the letter is not equal. If at least two keys are identical, you will run into problems because the keys must be unique. In fact, jq will only output one of the elements.
+2
source

Here's a slightly shorter option:

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

After correcting the input and using the jq -c option, this will result in two lines:

 [1,2,3] ["a","a",3] 
+5
source

Source: https://habr.com/ru/post/1263835/


All Articles