I am trying to access the field "my-tag" from the following json using jq from a shell script:
json file:
{
"tag": {
"value": "hello"
},
"my-tag": {
"value": "hello-my-tag"
}
}
Shell script:
#!/bin/bash
main()
{
search="my-tag"
file="myjson.json"
value=($(jq ".$search.value" "$file"))
echo $value
}
main "$@"
On executing this script, I get the following error:
error: tag is not defined
.-tag.value
^^^
1 compile error
How can I extract the field correctly in the shell script?
As a general rule of thumb, I would strongly suggest not placing shell variables within your filters, and use arguments to pass them in.
jq --arg search "$search" '.[$search].value' "$file"
Your filter string is an equivalent to a script. You wouldn't want to modify your script every time you wanted to change a value, you would parameterize it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With