在curl和jq上结合管道和重定向

在curl和jq上结合管道和重定向

如果我卷曲到某个网站,我可以直接得到 json:

curl http://httpbin.org/ip

{ "origin": "37.77.126.22"}

为了美化,我这样做:

curl http://httpbin.org/ip | jq

{
   "origin": "37.77.126.22"
}

为了美化它并保存它,我重定向......但它不起作用

curl http://httpbin.org/ip | jq > output.txt

{
   "origin": "37.77.126.22"
}

(23) Failed writing body

应该怎么做呢?

答案1

我很惊讶您在最后一个示例中获得了 JSON 输出,但这可能是问题中的剪切和粘贴错误。

在我的系统上,jq输出一条错误消息,其中还包含使用信息:

$ curl "http://httpbin.org/ip" | jq >file
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    33  100    33    0     0    115      0 --:--:-- --:--:-- --:--:--   136
(23) Failed writing body

“写入正文失败”来自于curl由于jq错误而退出并且无法读取正文(网页内容)。


写入终端以外的任何东西,jq1.5 需要一个过滤表达式。最简单的过滤器是.(点),它的作用类似于“直通”过滤器(上面的使用信息中称为“身份过滤器”):

$ curl "http://httpbin.org/ip" | jq . >file

更高版本jq默认使用身份过滤器,即使在写入文件或管道时,在没有显式给出过滤器的情况下也是如此。

相关内容