0

I'm tring to set a new variable with the piped output of another variable but it is not working. What's wrong with my syntax?

Using command substition $()

a="{\"a\": 1}"
echo $a
# output is: {a: 1} 
echo $a | jq '.a'
# output is: 1
b=$($a | jq '.a')
# error: {"a":: command not found

Without command substition

b=$a | jq '.a'
# b is empty
Botje
  • 26,269
  • 3
  • 31
  • 41
Lobstw
  • 489
  • 3
  • 18

1 Answers1

0

jq can process a JSON contained in a variable without using echo or <<<here-string.

#!/usr/bin/env bash

a='{"a": 1}'
echo "$a"
# output is: {a: 1} 
jq -n "$a | .a"
# output is: 1
b=$(jq -n "$a | .a")
# b=1
echo "$b"
# output is: 1

EDIT:

As Charles Duffy noted, it is a better practice to transmit the JSON as an argument, to prevent jq language directives injection from the input:

#!/usr/bin/env sh

a='{"a": 1}'
echo "$a"
# output is: {a: 1} 
jq -n --argjson a "$a" '$a | .a'
# output is: 1
b=$(jq -n --argjson a "$a" '$a | .a')
# b=1
echo "$b"
# output is: 1
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
  • 1
    Not particularly good practice, though -- less room for surprises if `jq -n --argjson a "$a" '$a | .a'` is used, so only actual JSON and not other JQ expressions can be present in `$a`. – Charles Duffy Nov 25 '21 at 20:19