how to escape single quote in `jq`
Asked Answered
R

1

8

I am trying to format a json string using jq with expected output like this:

[
  {
    "command": [
      "printf 'this is a text'"
    ]
  }
]

However, I cannot get it to work for the single quotes ('), e.g. $ jq -n '[{"command": ["printf 'this is a text'"]}]' gives me a compile error.

I also thought about escaping all double quotes e.g. jq -n "[{\"command\": [\"printf 'this is a text'\"]}]", this is fine however the json string is passed in from a function, I can replace all double quotes with \" first and then run the jq command but it's not very elegant.

Is there a better way to handle the single quotes inside a json string?

Rhu answered 30/10, 2020 at 0:18 Comment(1)
In Bash, a single quote cannot be explicitly included in a single-quoted string.Diction
B
11

Here are four alternatives that should work with a bash or bash-like shell. They can be adapted for other shells as well.

jq -n $'[{"command": ["printf \'this is a text\'"]}]'
cat << EOF | jq .
[{"command": ["printf 'this is a text'"]}]
EOF
jq --arg cmd "printf 'this is a text'" -n '[{command: [ $cmd ]}]'
VAR="[{\"command\": [\"printf 'this is a text'\"]}]"
jq -n --argjson var "$VAR" '$var'

See also How to escape single quotes within single quoted strings

Bridget answered 30/10, 2020 at 1:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.