如何在 shell 管道中使用 `jq`?
How to use `jq` in a shell pipeline?
我似乎无法让 jq
在 shell 管道中“正常”运行。例如:
$ curl -s https://api.github.com/users/octocat/repos | jq | cat
导致 jq
简单地打印出其帮助文本*。如果我尝试将 jq
的输出重定向到一个文件,也会发生同样的事情:
$ curl -s https://api.github.com/users/octocat/repos | jq > /tmp/stuff.json
如果 jq
确定它不是来自 tty 运行,它是否故意退出?我怎样才能防止这种行为,以便我可以在管道中使用 jq
?
编辑:看起来这在 jq
的最新版本中不再是问题。我现在有 jq-1.6
,上面的示例按预期工作。
* (我意识到这个例子包含一个useless use of cat;它仅用于说明目的)
您需要提供一个过滤器作为参数。要使 JSON 通过默认情况下 jq
提供的漂亮打印以外的未经修改的传递,请使用身份过滤器 .
:
curl -s https://api.github.com/users/octocat/repos | jq '.' | cat
我发现自己经常做的一个用例是 "How do I construct JSON data to supply into other shell commands, for example curl
?" 我这样做的方法是使用 --null-input/-n
选项:
Don’t read any input at all! Instead, the filter is run once using null
as the input. This is useful when using jq
as a simple calculator or to construct JSON data from scratch.
以及将其传递给 curl
的示例:
jq -n '{key: "value"}' | curl -d @- \
--url 'https://some.url.com' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json'
我似乎无法让 jq
在 shell 管道中“正常”运行。例如:
$ curl -s https://api.github.com/users/octocat/repos | jq | cat
导致 jq
简单地打印出其帮助文本*。如果我尝试将 jq
的输出重定向到一个文件,也会发生同样的事情:
$ curl -s https://api.github.com/users/octocat/repos | jq > /tmp/stuff.json
如果 jq
确定它不是来自 tty 运行,它是否故意退出?我怎样才能防止这种行为,以便我可以在管道中使用 jq
?
编辑:看起来这在 jq
的最新版本中不再是问题。我现在有 jq-1.6
,上面的示例按预期工作。
* (我意识到这个例子包含一个useless use of cat;它仅用于说明目的)
您需要提供一个过滤器作为参数。要使 JSON 通过默认情况下 jq
提供的漂亮打印以外的未经修改的传递,请使用身份过滤器 .
:
curl -s https://api.github.com/users/octocat/repos | jq '.' | cat
我发现自己经常做的一个用例是 "How do I construct JSON data to supply into other shell commands, for example curl
?" 我这样做的方法是使用 --null-input/-n
选项:
Don’t read any input at all! Instead, the filter is run once using
null
as the input. This is useful when usingjq
as a simple calculator or to construct JSON data from scratch.
以及将其传递给 curl
的示例:
jq -n '{key: "value"}' | curl -d @- \
--url 'https://some.url.com' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json'