JQおよびbashスクリプトを使用したJSONリクエストのフィルタリング

JQおよびbashスクリプトを使用したJSONリクエストのフィルタリング

次の内容を含むJSONをTwitchに要求します。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"

おすすめ記事