Reputation: 289
I am trying to query json using jq in bash scripting
file customers.json contains the following
[
{
"_id": "5968dd23fc13ae04d9000001",
"product_name": "sildenafil citrate",
"supplier": "Wisozk Inc",
"quantity": 262,
"unit_cost": "$1047"
},
{
"_id": "5968dd23fc13ae04d9000002",
"product_name": "Mountain Juniperus ashei",
"supplier": "Keebler-Hilpert",
"quantity": 292,
"unit_cost": "$874"
},
{
"_id": "5968dd23fc13ae04d9000003",
"product_name": "Dextromathorphan HBr",
"supplier": "Schmitt-Weissnat",
"quantity": 211,
"unit_cost": "$2053"
}
]
when i run following bash script
key="supplier"
value="Wisozk Inc"
jq ".[] | select(.$key==$value)" customers.json
It throws the following error
jq: error: syntax error, unexpected IDENT, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
.[] | select(.supplier == Wisozk Inc)
jq: 1 compile error
I think the space between "Wisozk" and "Inc" is the problem, what to do?
Upvotes: 1
Views: 320
Reputation: 85780
Do not let your shell variables to be interpolated in jq
under double quotes. The error is because of spaces in the value field, the variable $value
undergoes word-splitting by and the filter expression of jq
gets two words Wisozk
and Inc
instead of "Wisozk Inc"
.
Just pass your variables to jq
's context using the --arg
field and let it deal with it.
jq --arg k supplier --arg v "Wisozk Inc" 'map(select(.[$k] == $v))' json
This question is in parts duplicate to both the below questions, but not as a whole.
Upvotes: 3