JQ 및 bash 스크립팅으로 JSON 요청 필터링

JQ 및 bash 스크립팅으로 JSON 요청 필터링

Twitch에서 JSON을 요청합니다. 내 기능에 대해 보내는 입력은 curl --silent -H 'Accept: application/vnd.twitchtv.v3+json' -X GET https://api.twitch.tv/kraken/streams/$1어디에 있습니까?$1

이제 제가 목표로 하는 것은 컬 뒤에 이것을 파이핑하여 JSON을 필터링하는 것입니다. | jq '.stream.channel.something' jq 필터링을 통해 3개의 다른 문자열 값을 얻으려고 합니다. 이 수준으로 관리할 수 있습니다.

{
    "first": "lor"
    "second": "em"
    "third": "ipsum"
}

코드 내부에서 작동하는 방법은 무엇입니까?


내가 생각해낸 대안은 다음과 같습니다.

  1. 컬의 출력을 생성하고 필터링한 다음 삭제합니다.
  2. 3개의 cURL 요청 보내기 -- (쓸데없는 성능 저하?)

답변1

앞서 말했듯이 저는 json이나 jq에 대해 잘 모르지만 jq에서 다음 샘플 출력을 구문 분석하도록 할 수 없었습니다.

{
    "first": "lor"
    "second": "em"
    "third": "ipsum"
}

parse error: Expected separator between values at line 3, column 12

그래서 입력을 다음과 같이 바꿨습니다.

{
  "stream" : {
    "channel" : {
      "something" : {
        "first": "lor",
        "second": "em",
        "third": "ipsum"
      }
    }
  }
}

... jq에 대한 귀하의 통화에서 수집한 내용을 기반으로 합니다. 컬 명령이 출력하는 것과 유사하기를 바랍니다.

그렇다면 다음 순서로 원하는 것을 얻을 수 있는 것 같습니다.

# this is just your original curl command, wrapped in command substitution,
# in order to assign it to a variable named 'output':
output=$(curl --silent -H 'Accept: application/vnd.twitchtv.v3+json' -X GET https://api.twitch.tv/kraken/streams/$1)

# these three lines take the output stream from above and pipe it to
# separate jq calls to extract the values; I added some pretty-printing whitespace
first=$( echo "$output" | jq '.["stream"]["channel"]["something"]["first"]' )
second=$(echo "$output" | jq '.["stream"]["channel"]["something"]["second"]')
third=$( echo "$output" | jq '.["stream"]["channel"]["something"]["third"]' )

결과는 다음과 같습니다.

$ echo $first
"lor"
$ echo $second
"em"
$ echo $third
"ipsum"

답변2

파일이 유효한 JSON(질문의 데이터가 아님)이라고 가정합니다.

{
  "first": "lor",
  "second": "em",
  "third": "ipsum"
}

jq이를 사용하여 셸에서 안전하게 평가할 수 있는 세 가지 할당을 생성 할 수 있습니다 .

eval "$(
    jq -r '
        @sh "first=\(.first)",
        @sh "second=\(.second)",
        @sh "third=\(.third)"' file.json
)"

연산자 @sh는 쉘이 평가할 jq양식에 할당을 출력합니다 .first='lor'

셸 의 경우 bash배열 할당을 만들 수도 있습니다.

eval "$(
    jq -r '@sh "array=(\([.first, .second, .third]))"' file.json
)"

여기서 jq명령은 다음과 같은 것을 생성합니다 array=('lor' 'em' 'ipsum'). 이는 에 의해 평가될 때 주어진 내용으로 bash호출되는 배열을 생성합니다 .array

각 값이 스칼라라고 가정하고 jq명령문을 사용하여 모든 키 값의 배열을 생성할 수 있습니다 .@sh "array=(\([.[]]))"

관련 정보