使用 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

現在我的目標是透過在curl之後透過管道來過濾JSON:| jq '.stream.channel.something' 我試圖透過jq過濾取得3個不同的字串值我可以設法將它們達到這個等級:

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

如何在程式碼中操作它們?


我想出的替代方案是:

  1. 建立curl 的輸出,對其進行過濾,然後刪除。
  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 的電話中收集到的信息。希望這與 curl 命令的輸出類似。

如果是,那麼這個序列似乎可以滿足您的需求:

# 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它來建立三個分配,您可以在 shell 中安全地評估它們:

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

運算@sh子 injq將在表單上輸出賦值,first='lor'供 shell 進行計算。

對於bashshell,您也可以建立陣列分配:

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

在這裡,該jq命令將產生類似 的內容array=('lor' 'em' 'ipsum'),當 進行評估時,將建立使用給定內容bash呼叫的陣列。array

您可以使用該jq語句@sh "array=(\([.[]]))"建立所有鍵值的數組,假設每個值都是標量。

相關內容