The main problem seems to be in your json data because you have:
{'a': 'apple', 'b', 'bananna'}
As far as I know using single quotes is not valid (use double quotes): json format.
The another problem I see is that you have a comma ,
between 'b'
and 'bannana'
(I assume you didn't notice that and you typed ,
instead of :
)
So Your json data should be like this:
{"a": "apple", "b": "bananna"}
What is the proper syntax to get a key?
I usually see that the syntax '.key'
is more used. However I think you should use any which works. For example, I see in your case that you are using a variable $key
to get specific value from a json key. So, you should use something like ".$key"
or maybe ."$key"
, .$key
(I'm not sure if these are recommended):
Solution 1
FRUIT=$(echo $ALIASES | jq ".$key" -r)
#or
FRUIT=$(echo $ALIASES | jq ."$key" -r)
#or
FRUIT=$(echo $ALIASES | jq .$key -r)
If you use or want to use single quotes
then you will not be able to pass any variable value to jq
command. According to man bash
:
Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash
Therefore If you want to use single quotes
to a json value by specifying some key you should use:
FRUIT=$(echo $ALIASES | jq '.somekey' -r)
#e.g.
FRUIT=$(echo $ALIASES | jq '.a' -r)
echo $FRUIT
#Output:
apple
You can check these answers for a better understanding about single quotes
and double quotes
Solution 2 (using jq --arg)
I'm not sure why the code above doesn't work for you (using the double quotes). However there is another possible solution to pass variables to jq
, you can try:
val="a"
echo $ALIASES | jq --arg key "$val" '.[$key]' -r
As you are using python to get the json then you should use the method json.dumps(your_json)
, for example:
python3 -c 'import json;aliases = json.load(open("file"));print(json.dumps(aliases))'
$ALIASES
and$KEYS
are. Given the JSON in the code, that should generate aparse error: Invalid numeric literal
message, unless the value in$key
is not a valid JSON key.jq
directly. This would probably only involve a single invocation ofjq
instead of startingjq
once for each key.