对 jq 数组中的每个项目运行命令

问题描述 投票:0回答:2

这就是我的输入文件的样子:

[
  {
    "ConfigType": "ABC",
    "Prop1": 3,
    "Prop2": 30
  },
  {
    "ConfigType": "XYZ",
    "Prop3": "Hello",
    "Prop4": "World",
    "Prop5": "Application"
  }
]

我需要为每一项准备插入语句。

这就是我的 jq 命令的样子,它为我提供了每个项目。

cat app-cnfg.json |  jq -r ".[]"

如何执行

aws dynamodb put-item --table-name "xxx" --item <<array's element>>

bash jq
2个回答
24
投票

您可以通过管道传输到

xargs

jq -c '.[]' app-cnfg.json \
    | xargs -L 1 aws dynamodb put-item --table-name "xxx" --item

jq 的

-c
选项确保每个元素都在一行上,
-L 1
xargs
选项确保每个项目调用一次该命令。

如果您想避免尾随空格的潜在问题(这将使

args
将下一行视为当前行的延续),您可以让对象以零字节分隔(需要 jq 1.7 或更高版本):

jq -c --raw-output0 '.[]' app-cnfg.json \
    | xargs -0 -n1 aws dynamodb put-item --table-name "xxx" --item

--raw-output0
选项的行为类似于
-r
,但使用NUL而不是换行符。

xargs -0 -n1
需要零字节分隔输入,并为每个参数运行一次命令。


对于 1.7 之前的 jq 版本:

jq -j '.[] | tostring + "\u0000"' app-cnfg.json \
    | xargs -0 -n1 aws dynamodb put-item --table-name "xxx" --item

-j
选项抑制来自jq的换行符,
tostring
对对象进行字符串化,
+ "\u0000"
附加零字节。


5
投票

您可以应用过滤器来提取 JSON 数组的每个元素,并将其提供给

bash
中的数组,然后迭代其内容。假设您有
bash
4.0 或更高版本,您可以使用
mapfile
命令 as

mapfile -t configArr < <(jq -c '.[]'  < app-cnfg.json)

现在我们循环数组,为每个配置项运行命令,

for config in "${configArr[@]}"; do
    aws dynamodb put-item --table-name "xxx" --item "$config"
done

(或)使用更有效的方式使用

while
循环和
read
命令从输入数据流中读取数据(适用于不支持
bash
mapfile
readarray
版本)

while IFS= read -r config; do
    aws dynamodb put-item --table-name "xxx" --item "$config"
done< <(jq -c '.[]' < app-cnfg.json)
© www.soinside.com 2019 - 2024. All rights reserved.