Search code examples
jsonshellformattingjqquotation-marks

how to escape single quote in `jq`


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?


Solution

  • 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