curl と jq でパイプとリダイレクトを組み合わせる

curl と jq でパイプとリダイレクトを組み合わせる

あるサイトに curl すると、直接 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

「本文の書き込みに失敗しました」というメッセージは、エラーにより終了し、本文 (Web ページの内容) を読み取ることができない場合curlに発生します。jq


ターミナル以外のものに書き込む場合、jq1.5 ではフィルター式が必要です。最も単純なフィルターは.(dot) で、これは「パススルー」フィルター (上記の使用情報では「アイデンティティ フィルター」と呼ばれているもの) のように機能します。

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

以降のバージョンではjq、ファイルまたはパイプに書き込むときでも、フィルターが明示的に指定されていない場合は、デフォルトで ID フィルターが使用されます。

関連情報