首页 > 解决方案 > 使用 jq 遍历 json 数组的 Bash 循环

问题描述

我想遍历 json 数组,我写了这个简单的脚本,但我收到了这个错误

#! /bin/bash


m=$(jq '.items.item | length' try4.json)

for i in $(seq 1 10);
do
    jq --raw-output --arg v $i '.items.item[$v].request.text' try4.json | base64 --decode | sed '1q;d' | awk '{print $2}'
done

错误

jq: error (at try4.json:58): Cannot index array with string "1"
jq: error (at try4.json:58): Cannot index array with string "2"
jq: error (at try4.json:58): Cannot index array with string "3"
jq: error (at try4.json:58): Cannot index array with string "4"
jq: error (at try4.json:58): Cannot index array with string "5"
jq: error (at try4.json:58): Cannot index array with string "6"
jq: error (at try4.json:58): Cannot index array with string "7"
jq: error (at try4.json:58): Cannot index array with string "8"
jq: error (at try4.json:58): Cannot index array with string "9"
jq: error (at try4.json:58): Cannot index array with string "10"

标签: bashjq

解决方案


使用--argjson而不是--arg. 这样你的变量v就变成了一个数字jq,而不是一个字符串。

jq --raw-output --argjson v $i '.items.item[$v].request.text' try4.json | base64 --decode | sed '1q;d' | awk '{print $2}'

推荐阅读