-1

Question:

How do I build JSON using JQ in bash using something like the following? (The output is not as expected - explanation below)

Test1="*/15 * * * *"
json=$( jq -n --arg bob "$Test1" '{ Kate: $bob}' )

Problem:

Bash tries to be helpful when echoing the content of the string. In this case, the * character is interpreted as the contents of the current directory.

An example of the problem: If I have a subfolder called test in the current directory and I do the following:

:$ Test1="*/15 * * * *"
:$ echo $Test1
:$ */15 test test test test

Obviously, I don't want the folder name substituted for the asterix. I can get around this by putting the variable in quotes - this outputs the correct string.

:$ Test1="*/15 * * * *"
:$ echo "$Test1"
:$ */15 * * * *

However, when I attempt to build a JSON object using this string with JQ, I get the following:

:$ Test1="*/15 * * * *"
:$ json=$( jq -n --arg bob "$Test1" '{ Kate: $bob}' )
:$ echo $json
:$ { "Kate": "*/15 test test test *" }

I want the output to be

{ "Kate": "*/15 * * * *" }

How can I achieve this using JQ?
Also - why is the last star not interpreted in the JSON object? I would have expected to see four instances of the folder name, but I see three, followed by an asterix.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Jay
  • 9,561
  • 7
  • 51
  • 72

2 Answers2

2

The problem is not with your invocation of jq, but with the way you examined jq's output. When confronted with this type of puzzle, you can usually figure out the problem by examining intermediate results. So consider:


$ Test1="*/15 * * * *"

$ echo "$Test1"
*/15 * * * *

$ jq -n --arg bob "$Test1" '{ Kate: $bob}'
{
  "Kate": "*/15 * * * *"
}

$ json=$(jq -n --arg bob "$Test1" '{ Kate: $bob}')

$ echo "$json"
{
  "Kate": "*/15 * * * *"
}

Trailing asterisk

Similarly, for the second question about the trailing asterisk:

$ echo "$Test1"
*/15 * * * *

$ echo $Test1
*/15 test test test test

$ echo \"$Test1\"
"*/15 test test test *"

peak
  • 105,803
  • 17
  • 152
  • 177
  • Yes, thank you - this was driving me mad. putting quotes round the variable when I examined it is exactly what I should have done. – Jay Nov 26 '20 at 11:03
0

To stop wildcard expansion in your bash shell, you can:

set -o noglob

Then to add it back in:

set +o noglob
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18