A
A
Alexey Babiev2020-06-10 13:17:28
bash
Alexey Babiev, 2020-06-10 13:17:28

How to use jq to add a value from a variable containing spaces?

json="{}"
foo="Without_spaces"
bar="With spaces"
json=$(jq '.one = "Without_spaces"' <<< $json)
json=$(jq '.two = "With spaces"' <<< $json)
json=$(jq '.foo = "'$foo'"' <<< $json)
# json=$(jq '.bar = "'$bar'"' <<< $json)
jq . <<< $json

The script generates a JSON object. Key values ​​are placed in a variable, then added to an object. And now a situation arose when the variable contains a line with spaces (commented out line). jq throws an error
jq: error: syntax error, unexpected $end, expecting QQSTRING_TEXT or QQSTRING_INTERP_START or QQSTRING_END (Unix shell quoting issues?) at <top-level>, line 1:
.bar = "With        
jq: 1 compile error

If the value with a space is hardcore written in the code, then there is no error (key two)
How to overcome it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xotkot, 2020-06-10
@axsmak

json=$(jq --arg v "$bar" '.bar = $v' <<< $json)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question