3

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

mklement0
  • 382,024
  • 64
  • 607
  • 775
ssenator
  • 133
  • 1
  • 8

1 Answers1

1

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.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • This works! I do not understand why, though - about_Quoting_Rules in PowerShell states "When you enclose a string in single-quotation marks (a single-quoted string), the string is passed to the command exactly as you type it. No substitution is performed.", so what in the world is going on? Why are the backslashes being processed, and by what process? – ssenator Nov 30 '20 at 15:48
  • @ssenator This is not an escape method for PowerShell. This must be calling the cmd shell to run the executable. Once inside of single quotes, the inner contents are read literally in PowerShell. – AdminOfThings Nov 30 '20 at 17:13
  • 2
    @ssenator: The sad truth is that PowerShell's argument passing to external programs has always been broken and still is as of v7.1 - and there's resistance to fixing that, for fear of breaking existing workarounds, such as the one shown in this answer - see [this answer](https://stackoverflow.com/a/59036879/45375) to one of the linked duplicates for background information. – mklement0 Nov 30 '20 at 17:32