объединить трубу и перенаправить на 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

«Ошибка записи тела» исходит от curlas, jqбыл завершен из-за ошибки и недоступен для чтения тела (содержимого веб-страницы).


Запись на что-либо, кроме терминала, jq1.5 требует выражения фильтра. Самый простой фильтр — .(точка), который действует как «сквозной» фильтр (то, что называется «фильтром идентификации» в информации об использовании выше):

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

Более поздние версии jqиспользуют фильтр идентификации по умолчанию, даже при записи в файл или канал, в случае, если фильтр явно не указан.

Связанный контент