gpt4 book ai didi

bash - JQ 仅在重定向 stdout 时才给出使用错误

转载 作者:行者123 更新时间:2023-12-03 20:17:28 29 4
gpt4 key购买 nike

我有一个 curl 命令

 curl -H "Accept: application/json" https://icanhazdadjoke.com/

它返回 JSON(注意:我选择这个 api 是因为它没有身份验证所以每个人都可以帮助测试,它返回一个格式化的 json 但大多数 API 返回一个没有格式的平面 json...一行)
 {
"id": "5wAIRfaaUvc",
"joke": "What do you do when a blonde throws a grenade at you? Pull the pin and throw it back.",
"status": 200
}

当我通过管道传输到 JQ 时,jq 会按预期响应。我通过管道连接到 jq 以确保我有一个格式化的可读 json
curl -H "Accept: application/json" https://icanhazdadjoke.com/ | jq

退货

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload Upload Total Spent Left Speed
100 110 100 110 0 0 320 0 --:--:-- --:--:-- --:--:-- 321
{
"id": "NCAIYLeNe",
"joke": "I fear for the calendar, it’s days are numbered.",
"status": 200
}

但是当我将 JQ 的输出通过管道传输到文本文件时(我希望保存格式化版本以提高可读性,而不是普通的未格式化的 json)我收到一个错误
curl -H "Accept: application/json" https://icanhazdadjoke.com/ | jq > file.txt

退货

jq - commandline JSON processor [version 1.5]
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
filter's results as JSON on standard output.
The simplest filter is ., which is the identity filter,
copying jq's input to its output unmodified (except for
formatting).
For more advanced filters see the jq(1) manpage ("man jq")
and/or https://stedolan.github.io/jq

Some of the options include:
-c compact instead of pretty-printed output;
-n use `null` as the single input value;
-e set the exit status code based on the output;
-s read (slurp) all inputs into an array; apply filter to it;
-r output raw strings, not JSON texts;
-R read raw strings, not JSON texts;
-C colorize JSON;
-M monochrome (don't colorize JSON);
-S sort keys of objects on output;
--tab use tabs for indentation;
--arg a v set variable $a to value <v>;
--argjson a v set variable $a to JSON value <v>;
--slurpfile a f set variable $a to an array of JSON texts read from <f>;
See the manpage for more options.
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 141 100 141 0 0 317 0 --:--:-- --:--:-- --:--:-- 316
(23) Failed writing body

最佳答案

如果你想要 jq要格式化与输入相同的 JSON,请传递 .作为它运行的脚本:

curl -H "Accept: application/json" https://icanhazdadjoke.com/ | jq . > file.txt
来自 the manual :

Identity: .

The absolute simplest filter is . . This is a filter that takes its input and produces it unchanged as output. That is, this is the identity operator.

Since jq by default pretty-prints all output, this trivial program can be a useful way of formatting JSON output from, say, curl.

关于bash - JQ 仅在重定向 stdout 时才给出使用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47578328/

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