컬과 jq에서 파이프와 리디렉션 결합

컬과 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에는 필터 표현식이 필요합니다. 가장 간단한 필터는 ."통과" 필터처럼 작동하는 (점)입니다(위 사용 정보에서는 "ID 필터"라고 함).

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

이후 버전에서는 jq필터가 명시적으로 지정되지 않은 경우 파일이나 파이프에 쓸 때에도 기본적으로 ID 필터를 사용합니다.

관련 정보