【发布时间】:2017-11-30 16:39:21
【问题描述】:
我有一个 curl 命令
curl -H "Accept: application/json" https://icanhazdadjoke.com/
返回JSON(注意:我选择这个api是因为它没有auth所以每个人都可以帮助测试,它返回一个格式化的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
【问题讨论】:
-
也就是说,
icanhazdadjoke的输出实际上并没有作为一行返回。您在问题中将其显示为几行,当我自己运行它时,我将它分几行(已经打印得很漂亮)。 -
是的,如果您阅读了我的问题的注释部分,我会说这个 API 确实返回了漂亮的打印。我正在研究一个没有身份验证的 API,为 stackoverflow 找出一个没有身份验证的 API
-
明白了。感谢您为制作其他人可以使用的复制器所做的努力。为了将来注意,ix.io 和 sprunge.us 都是无广告的粘贴箱,带有记录在案的
curl友好界面,通过这些界面可以管道文件并让人们得到完全相同的位;对于这种示例很有用。很确定gist.github.com 也有一个原始界面,但必须查看(而 ix/sprunge 预先记录他们的)。 -
如果标准输出是终端,则调用
jq可以省略过滤器这一事实似乎没有记录。