在 PowerShell 中使用 jq 中的 $ 变量

kob*_*a23 3 powershell json jq

我正在使用此代码:

jq --raw-output "(map(keys) | add | unique) as $cols | map(. as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv" output2.json > output3.csv
Run Code Online (Sandbox Code Playgroud)

从我的 JSON 数据库创建 CSV:

jq --raw-output "(map(keys) | add | unique) as $cols | map(. as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv" output2.json > output3.csv
Run Code Online (Sandbox Code Playgroud)

https://jqplay.org/上的输出是完美的,但在我的命令行上运行时似乎根本不起作用。我在 VSCode 中使用 PowerShell。

我不断收到此错误。

jq: 错误: 语法错误,意外的“|”,期待“$”或“[”或“{”(Windows cmd shell 引用问题?)在, 
第 1 行:(map(keys) | add | unique) as | map(. as | | map([.])) as | , [] | @csv
jq: 1 编译错误

我猜是$问题所在,因为它们没有显示在错误文本中,所以我尝试以各种方式逃避它们,但没有取得任何进展。我已经进行了广泛的搜索,似乎没有人有这个问题,所以我一定得到了一些非常简单非常错误的东西。

mkl*_*nt0 6

你的jq脚本:

  • 必须作为文字PowerShell 字符串 ( '...')传递
  • 因为一个内插的PowerShell串("...")由设计解释$-prefixed令牌作为PowerShell的变量引用; 例如,$cols(或 PowerShell子表达式( $(...)),在这种情况下不适用):
jq -r '(map(keys) | add | unique) as $cols | 
       map(. as $row | $cols | map($row[.])) as $rows | 
         $cols, $rows[] | @csv' output2.json > output3.csv
Run Code Online (Sandbox Code Playgroud)

* 为了便于阅读,我添加了换行符。PowerShell 字符串文字可以跨越多行,因此您应该能够按原样粘贴多行命令。当然,您可以将其格式化为单行。
*-r确保结果是“原始”输出,即没有 JSON 值转义。
* 如果您将jq脚本保存到要与该选项一起使用的文件-f,请确保将其保存为 UTF-8而不带 BOM


这是一个演示差异的简化示例:

# OK: SINGLE-quoted jq script:
PS> '{ "foo": "bar" }' | jq '. as $cols | .foo'
"bar"

# BROKEN: DOUBLE-quoted jq script: PowerShell expands `$cols` up front, 
#         resulting in an empty string, if no such PowerShell variable exists. 
#         jq then effectively sees '. as  | .foo', which explains the syntax error.
PS> '{ "foo": "bar" }' | jq ". as $cols | .foo"
jq: error: syntax error, unexpected '|', expecting '$' or '[' or '{' (Unix shell quoting issues?) at <top-level>, line 1:
. as  | .foo      
jq: 1 compile error
Run Code Online (Sandbox Code Playgroud)