JSON配列をBashに変換

JSON配列をBashに変換

私はJQクイズデータベースからいくつかのJSONを取得するために使用しており、結果を解析したいと思います。以下のように結果配列を Bash に保存しようとしていますが、型が Bash スタイルではなく JavaScript/Python で使用される括弧型です。

quiz=$(curl -s https://opentdb.com/api.php?amount=3)
answers=$(echo $quiz | jq '[ .results][0][0].incorrect_answers')
correct=$(echo $quiz | jq '[ .results][0][0].correct_answer')
answers+=( $correct )

答えの例は次のとおりです。

[ "Excitement", "Aggression", "Exhaustion" ]

奇形のため、正解は配列にプッシュされません。

スクリプトで配列として解釈されるように、上記の形式の配列をどのように変換できますか?

出力例curl (ハードコードされていないため、質問と回答は毎回異なります):

{
  "response_code": 0,
  "results": [
    {
      "category": "Entertainment: Television",
      "type": "multiple",
      "difficulty": "easy",
      "question": "Which company has exclusive rights to air episodes of the "The Grand Tour"?",
      "correct_answer": "Amazon",
      "incorrect_answers": [
        "Netflix",
        "BBC",
        "CCTV"
      ]
    },
    {
      "category": "Celebrities",
      "type": "multiple",
      "difficulty": "medium",
      "question": "How much weight did Chris Pratt lose for his role as Star-Lord in "Guardians of the Galaxy"?",
      "correct_answer": "60 lbs",
      "incorrect_answers": [
        "30 lbs",
        "50 lbs",
        "70 lbs"
      ]
    },
    {
      "category": "Animals",
      "type": "boolean",
      "difficulty": "easy",
      "question": "The Killer Whale is considered a type of dolphin.",
      "correct_answer": "True",
      "incorrect_answers": [
        "False"
      ]
    }
  ]
}

ベストアンサー1

jq結果を1行ずつ出力します。次に、bashmapfileコマンドを使用して行を配列に読み込みます。

mapfile -t correct < <(jq -r '.results[] | .correct_answer' <<<"$quiz")
declare -p correct
declare -a correct=([0]="Amazon" [1]="60 lbs" [2]="True")

誤解の場合、bashには多次元配列がないため、jq誤解をCSVに出力できます。

mapfile -t incorrect < <(jq -r '.results[] | .incorrect_answers | @csv' <<<"$quiz")
declare -p incorrect
declare -a incorrect=([0]="\"Netflix\",\"BBC\",\"CCTV\"" [1]="\"30 lbs\",\"50 lbs\",\"70 lbs\"" [2]="\"False\"")

それから:

$ echo "q $i: ans=${correct[i]}; wrong=${incorrect[i]}"
q 1: ans=60 lbs; wrong="30 lbs","50 lbs","70 lbs"

文書:


ユーザーと対話しているとします。

i=0
read -p "Answer to question $i: " answer

if [[ $answer == "${correct[i]}" ]]; then
    echo Correct
elif [[ ${incorrect[i]} == *"\"$answer\""* ]]; then
    echo Incorrect
else
    echo Invalid answer
fi

[[...]]演算子==の内部にはいいえ文字列恒等演算子は次のとおりです。パターンマッチングオペレーター。

  • 最初のテストは単純な文字列比較です。
  • 2番目のテストでは、CVS文字列に誤った答えが含まれていることを確認します。含む回答二重引用符で囲む

おすすめ記事