Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: Accessing fields with - character in shell script

Tags:

json

shell

jq

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?

like image 353
sajus Avatar asked Apr 26 '26 16:04

sajus


1 Answers

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.

like image 112
Jeff Mercado Avatar answered Apr 28 '26 04:04

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!