为什么jq有时需要过滤器表达式,而有时则不需要过滤器表达式? [英] Why does jq sometimes require a filter expression, and sometimes not?
问题描述
我有一些未格式化的JSON文件.我想用jq格式化它们,然后通过less看到格式化的输出:
I have some unformatted JSON files. I want to format them with jq and see the formatted output via less:
cat *.json | jq | less
但是它不起作用.只是显示jq的帮助.
But it doesn't work. Just shows the jq's help.
好吧,jq需要一个过滤器,最少需要一个.
,但是...
O.K., jq needs a filter, minimum a .
, but...
cat *.json | jq
为我工作.
有什么区别?看到解析命令行是Shell的任务,这是Bash的错误吗?为什么只有jq会发生这种情况?
What is the difference? Is this a Bash bug, seeing that parsing the command line is the shell's task? Why does this only happen with jq?
推荐答案
jq
在检测到其输出流是终端的情况下会做一些不同的事情.一方面,它对输出进行颜色编码(除非您显式关闭该选项).但是与这个问题更相关的是,对于1.5版,如果它检测到其输出流是一个终端并且其输入流不是一个终端,并且根本没有任何非选项命令行参数,则假定您打算使用过滤器.
.
jq
does some things differently if it detects that its output stream is a terminal. For one thing, it colour-codes its output (unless you explicitly turn that option off). But more relevantly to this question, for version 1.5, if it detects that its output stream is a terminal and its input stream is not a terminal and there are no non-option command-line arguments at all, it assumes that you meant to use the filter .
.
因此,当您键入 cat * .json |时会发生这种情况.jq
.在这种情况下,jq的输入流是管道(来自 cat
命令),但其输出流是终端.因此,它假定默认过滤器为.
.
So that's what happens when you type cat *.json | jq
. In that case, jq's input stream is a pipe (from the cat
command) but its output stream is the terminal. So it assumes a default filter of .
.
但是,当通过 less
通过 jq
的输出传递管道时, jq
的输出流不再是终端.现在是一个管道(连接到一个 less
进程).因此,没有插入自动过滤器.
,并且 jq
抱怨没有提供过滤器.
But when you pipe the output of jq
through less
, jq
's output stream is no longer a terminal. Now it's a pipe (connected to a less
process). So the automatic filter .
is not inserted, and jq
complains that no filter was provided.
但是,如果升级到v1.6,您会发现行为已更改.在v1.6中,没有任何过滤器的调用将被调整为.
除非两者都是输入流和输出流都是终端.因此,如果升级,您会发现 cat * .json |jq |less
的工作方式与 cat * .json |大致相同jq
,除了输出是彩色的,当然不分页.
However, if you upgrade to v1.6, you'll find that the behaviour has changed. In v1.6, an invocation without any filter will be adjusted to .
unless both the input stream and the output stream are a terminal. So if you upgrade, you'll find that cat *.json | jq | less
works roughly the same way as cat *.json | jq
, except that the output is coloured and, of course, not paged.
顺便说一句,如果您想使用 less
(并且正在使用Gnu less
)查看彩色输出,则可以使用以下命令:
By the way, if you wanted to see coloured output with less
(and you're using Gnu less
), then you could use the command:
cat *.json | jq . -C | less -R # The . is not necessary with v1.6
这篇关于为什么jq有时需要过滤器表达式,而有时则不需要过滤器表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!