在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

「寫入正文失敗」來自於curljq錯誤而退出並且無法讀取正文(網頁內容)。


寫入終端以外的任何東西,jq1.5 需要一個過濾表達式。最簡單的過濾器是.(點),它的作用類似於“直通”過濾器(上面的使用資訊稱為“身份過濾器”):

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

更高版本jq預設使用身份過濾器,即使在寫入檔案或管道時,在沒有明確給出過濾器的情況下也是如此。

相關內容