66

I have the following JSON file with example values:

{
    "files": [{
        "fileName": "FOO",
        "md5": "blablabla"
    }, {
        "fileName": "BAR",
        "md5": "alaldlafj"
    }]
}

Now what I want is to return the md5 value where for example the fileName is "FOO". For this I have the following statement in jq:

cat <file>.json | jq '.[] | select(.fileName=="FOO")' 

However response back is: jq: error (at <stdin>:11): Cannot index array with string "fileName"

What is the correct way to return the md5 value where the key fileName equals a certain argument?

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Marvin Effing
  • 2,693
  • 3
  • 20
  • 35

3 Answers3

80

Found the answer:

cat <file>.json | jq -r '.files[] | select(.fileName=="FOO") | .md5'
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Marvin Effing
  • 2,693
  • 3
  • 20
  • 35
  • 20
    Why bring `cat` into this? You can simply `jq -r '.files[] | select(.fileName=="FOO") | .md5' ` – Brent D. Jun 17 '21 at 00:03
  • 8
    @BrentD. - You are right that your version is shorter and simpler. However, some such as myself strongly prefer the strictly left-to-right structure that beginning with `cat` provides, especially when pipes are involved. – bitinerant Dec 07 '22 at 18:59
  • 2
    A shorter, simpler line that maintains strict left-to-right ordering is ` – Scott Centoni May 25 '23 at 07:12
12

to answer the more generic how to select value from array selecting all filenames:

cat results.json | jq '.files[] | .filename'
jmunsch
  • 22,771
  • 11
  • 93
  • 114
7

or:

cat <file>.json | jq -r '.files[] | select(.fileName=="FOO").md5'
Rob Paisley
  • 437
  • 1
  • 3
  • 13
Alex Berger
  • 79
  • 1
  • 2
  • 9
    Welcome to Stackoverflow! Please consider reading [this](https://stackoverflow.com/help/how-to-answer) section to improve your answer. Can you provide an explanation for the code you have posted here? – Kevin Dec 03 '19 at 18:35