81

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?

4 Answers 4

101

Found the answer:

cat <file>.json | jq -r '.files[] | select(.fileName=="FOO") | .md5'
Sign up to request clarification or add additional context in comments.

4 Comments

Why bring cat into this? You can simply jq -r '.files[] | select(.fileName=="FOO") | .md5' <file.json>
@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.
A shorter, simpler line that maintains strict left-to-right ordering is <file.json jq -r '.files[] | select(.fileName=="FOO") | .md5'
Thinking of newbies cat file.json is a bit more readable than <file.json. I'm also on the cat file.json side as mostly that file.json is a mock and when the script goes live, it will replaced by the real data source that might contain cleanup and filter commands all piped together and that jq is just the last part of a bigger equation.
13

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

cat results.json | jq '.files[] | .filename'

1 Comment

The question was about selecting a specific field based on value of other field. Not about selecting all the fields.
7

or:

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

1 Comment

Welcome to Stackoverflow! Please consider reading this section to improve your answer. Can you provide an explanation for the code you have posted here?
4

If you want to keep your item in the array, so do more of a filter you can do

cat <file>.json | jq -r '.files | map(select(.fileName=="FOO").md5)'

this would result in

['blablabla']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.