Search code examples
powershellescapingjqquoting

String literals in JQ using PowerShell


I cannot get JQ string literals to work from Powershell. For example, this outputs a pretty JSON object in Bash, but fails in Powershell:

PS C:\temp> jq --null-input '{"key":"val"}'

jq: error: val/0 is not defined at <top-level>, line 1:
{key:val}
jq: 1 compile error

At first I suspected incorrect quoting, but Write-Output '{"key":"val"}' outputs {"key":"val"} as I would expect.

I can work around it by writing my JQ filter into a file. Using .NET WriteAllText ensures the file gets encoded as UTF-8 without BOM.

PS C:\temp> [System.IO.File]::WriteAllText('basic.jq', '{"key":"val"}')
PS C:\temp> jq --null-input --from-file basic.jq
{
  "key": "val"
}

I am looking for a more nimble approach for prototyping JQ filters and integrating them in PowerShell scripts.

Versions: JQ 1.6 for win64, PSVersion 5.1.18362.1171


Solution

  • Powershell might want you to escape the double-quotes inside the '..' expression. Try

    jq --null-input '{ "key": \"val\" }'
    

    or just below as the key names in jq don't need an explicit quote

    jq --null-input '{ key: \"val\" }'
    

    From the jq manual under - Invoking jq

    When using the Windows command shell (cmd.exe) it's best to use double quotes around your jq program when given on the command-line (instead of the -f program-file option), but then double-quotes in the jq program need backslash escaping.