Pipe

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

  • February 21, 2020

如果我捲曲到某個站點,我可以獲得直接的 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

應該怎麼做?

我有點驚訝您在第二個範例中得到 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

“Failed writing body”來自curlas jqhas exited 由於錯誤,無法讀取正文(網頁內容)。


jq需要一個過濾器表達式。最簡單的過濾器是.(dot),它的作用類似於“通過”過濾器(在上面的使用資訊中稱為“身份過濾器”):

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

引用自:https://unix.stackexchange.com/questions/367127