bash - 使用 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"
解决方案
使用--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}'
推荐阅读
- java - 为什么 .java 文件不能在 IDEA 中正确显示?
- c - 在手臂皮质上使用 GCC 引发对 __aeabi_fxxx 函数的长时间调用
- php - 如何获取yii2排序从低到高和从高到低的单独链接
- nativescript - Nativescript-Vue 问题与平移元素
- javascript - PostgreSQL 输出的时间戳格式与 Javascript 时间戳格式不同
- wget - wget 从网页中获取所有链接的文件
- ios - 如何在图表 ios 中设置自定义 x 轴 0 标签
- uitableview - 将行高设置为 0 swift 时,tableview 的最后一部分被打乱
- reactjs - React:提交表单后如何清除文件输入和数据输入字段?
- javascript - 如何按多个字段对值进行分组并按特定类型对其进行排序