File export from company system generates json in a structure that I cannot change. When searching through for specific attributes based on variables within bash (v5.0.2), it always returns null when using any element of substitution. If I hard code the value to be searched, it works. However, need to be able to use variables to support logic of code and to not have to hard code specifics, especially given 1000's of records to process.
Using the example extract of json below, and the code further below, this shows what I've tried based on what I can understand from jq manual.
{
"status": true,
"payload": {
"customerData": {
"101": {
"title": "A Company",
"id": "101",
"storageGroups": "SHIPPING",
"priority": "4",
"originalname": "A Previous Company",
"allowShipping": true,
"parentCompany": "0",
"rating": 0,
"external": false,
"application": "primary",
"applicationName": "form27",
"live": true,
"logo": "http://url",
"beta": false,
"length": null,
"token": "QSBQcmV2aW91cyBDb21wYW55LzEwMQ==",
"active": "1"
}
}
}
}
Simple bash script to evidence approaches tested so far
#!/bin/bash
chkCustomer=101
chkFile="json-simple.txt"
if [[ ! -s "${chkFile}" ]] ; then exit 1 ; fi
tokenTry1=$(cat "${chkFile}" | jq -r '.payload.customerData."${chkCustomer}".token')
printf "%s\n" "Try 1 Returned ${tokenTry1}"
tokenTry2=$(cat "${chkFile}" | jq -r '.payload.customerData."$chkCustomer".token')
printf "%s\n" "Try 2 Returned ${tokenTry2}"
tokenTry3=$(cat "${chkFile}" | jq -r --arg CHK ${chkCustomer} '.payload.customerData."$CHK".token')
printf "%s\n" "Try 3 Returned ${tokenTry3}"
tokenTry4=$(cat "${chkFile}" | jq -r --arg CHK ${chkCustomer} '.payload.customerData."env.$CHK".token')
printf "%s\n" "Try 4 Returned ${tokenTry4}"
tokenTry5=$(cat "${chkFile}" | jq -r --arg CHK 101 '.payload.customerData."$CHK".token')
printf "%s\n" "Try 5 Returned ${tokenTry5}"
tokenTry6=$(cat "${chkFile}" | jq -r '.payload.customerData.101.token')
printf "%s\n" "Try 6 Returned ${tokenTry6}"
tokenWorks=$(cat "${chkFile}" | jq -r '.payload.customerData."101".token')
printf "%s\n" "Try 7 (works) Returned ${tokenWorks}"
Only attempt 7 results in a valid response. All rest are either null
or a failure.
Output of the script against the json is
Try 1 Returned null
Try 2 Returned null
Try 3 Returned null
Try 4 Returned null
Try 5 Returned null
jq: error: Invalid numeric literal at EOF at line 1, column 5 (while parsing '.101.') at <top-level>, line 1:
.payload.customerData.101.token
jq: error: syntax error, unexpected LITERAL, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.payload.customerData.101.token
jq: 2 compile errors
Try 6 Returned
Try 7 (works) Returned QSBQcmV2aW91cyBDb21wYW55LzEwMQ==
What I need (or expect) is that I can use a variable and execute a jq query to get a result.
I'm sure I'm missing something mindbogglingly obvious, but I cannot fathom this. Looking at other questions I've found here on SO, none have yet helped.