1

I'm using Bash to run the following script snippet on a Linux box.

JSON file contents: [ { "id": 123456, "firstName": "John", "lastName": "Smith", "email": "user@domain.com" } ]


The JSON file is stored in the ${data[0]} array which is piped into the Bash script.


Bash script:

trafficEmployeeId=123456 cat "${data[0]}" | jq --arg employeeId $trafficEmployeeId '.[] | select(.id == $employeeId) | .firstName'


And the output from the script should be John. But I get nothing.

  • 1
    show your $trafficEmployeeId value – RomanPerekhrest Oct 20 '17 at 16:23
2

Even if you assigned shell variable trafficEmployeeId with a number it will be passed into jq script as a string argument.
The solution is to parse the argument as a number with jq's tonumber function.
The second moment is that data[0] contains the array with only one object, so it's enough to access it directly with .[0] and apply simple if operator condition.

Complete solution:

trafficEmployeeId=123456
echo "${data[0]}" | jq --arg employeeId "$trafficEmployeeId" '.[0] 
      | if .id == ($employeeId | tonumber) then .firstName else empty end'

The output:

"John"
  • On newer versions of jq, one could also use --argjson instead of tonumber. – dhag Oct 20 '17 at 16:47
  • Thanks for the advice. I'll try this solution and get back to you. – Berni Oct 20 '17 at 18:53
  • Your answer led me to the correct solution. Thanks a lot! – Berni Oct 20 '17 at 19:23

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.