33

This is a very basic (probably silly) 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]
    }
}

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

[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.

2 Answers 2

32

Your statement does not work, because you try to feed the data object into match, but match can only work on strings.

The following expression will do what you want. The to_entries converts the object to an array of keys and values. Then we iterate over this array by using map and select all entries where the .key (now a string) has a 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.
  • 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.
1
  • 3
    The two map calls can and should be combined. Feb 5, 2017 at 20:12
21

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:

[1,2,3]
["a","a",3]
1
  • 4
    I like this one, and helped me figure out to get all key:values if the key contains a patern (or is uniq) For all values where key name is "keynameSOMETHING" .data | with_entries(select(.key|match("keyname+";"ig")))[] For key:value with the same filer we just remove the [] at the end... and even works if I want to search more than one PATTERN in the keyname like: .data | with_entries(select(.key|match("contains1+", "contains2+"; "ig"))) couldn't done it without you're suggestion though @peak so thank
    – Mikec
    Apr 6, 2017 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.