gpt4 book ai didi

shell - 将输出通过管道传输到 jq 后写入文件

转载 作者:行者123 更新时间:2023-12-03 12:08:55 25 4
gpt4 key购买 nike

如何编写通过 jq 的管道输出到shell中的文件

例子:

curl api.example.com | jq > call.txt

不会工作。也没有
(curl api.example.com | jq) > call.txt

帮助!

编辑:这样做 curl api.example.com > call.txt工作得很好。所以它与管道它有关 jq

最佳答案

只需调用 jq如果 stdout,没有过滤器会抛出错误不是终端

$ curl https://jsonplaceholder.typicode.com/posts/1 | jq > test.txt
jq - commandline JSON processor [version 1.5-1-a5b5cbe]
Usage: jq [options] <jq filter> [file...]

jq is a tool for processing JSON inputs, applying the
given filter to its JSON text inputs and producing the
[...]

试试 jq '.' (即:漂亮地打印输入 JSON):

$ curl https://jsonplaceholder.typicode.com/posts/1 | jq '.' > test.txt
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 292 100 292 0 0 1698 0 --:--:-- --:--:-- --:--:-- 1707

请注意,过滤器并不是真正可选的:

来自 man jq :

JQ(1)                                                                                JQ(1)

NAME
jq - Command-line JSON processor

SYNOPSIS
jq [options...] filter [files...]

根据主分支的提示......你所描述的(和我观察到的)行为不是预期的......
jq 的旧版本有以下内容:( here )

if (!program && isatty(STDOUT_FILENO) && !isatty(STDIN_FILENO))
program = ".";

即:如果 stdout 使用默认过滤器是 TTY,和 stdin不是 TTY。

此行为似乎已在提交 5fe05367 中得到纠正。 ,使用以下代码片段:

if (!program && (!isatty(STDOUT_FILENO) || !isatty(STDIN_FILENO)))
program = ".";

关于shell - 将输出通过管道传输到 jq 后写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com