我有一个卷曲命令
curl -H "Accept: application/json" https://icanhazdadjoke.com/
Run Code Online (Sandbox Code Playgroud)
返回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
}
Run Code Online (Sandbox Code Playgroud)
当我管道到JQ时,jq按预期响应.我管道到jq以确保我有一个格式化的可读json
curl -H "Accept: application/json" https://icanhazdadjoke.com/ | jq
Run Code Online (Sandbox Code Playgroud)
返回
% 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
}
Run Code Online (Sandbox Code Playgroud)
但是当我将JQ的输出传输到文本文件时(我希望保存格式化版本以便于阅读,而不是普通的未格式化的json)我收到错误
curl -H "Accept: application/json" https://icanhazdadjoke.com/ | jq > file.txt
Run Code Online (Sandbox Code Playgroud)
返回
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
Run Code Online (Sandbox Code Playgroud)
如果要jq
格式化它作为输入获得的相同JSON,请将其.
作为脚本传递以运行:
curl -H "Accept: application/json" https://icanhazdadjoke.com/ | jq . > file.txt
Run Code Online (Sandbox Code Playgroud)
从手册:
身份:
.
绝对最简单的过滤器是
.
.这是一个过滤器,它接受输入并将其作为输出保持不变.也就是说,这是身份运营商.由于jq默认打印所有输出,这个简单的程序可以是一种有用的格式化JSON输出的方式,比如说
curl
.