Parsing JSON with JQ

Berni

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

JSON file contents: [ { "id": 123456, "firstName": "John", "lastName": "Smith", "email": "[email protected]" } ]


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.

RomanPerekhrest

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"

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사