从 jq 使用 json 参数运行 bash 命令

从 jq 使用 json 参数运行 bash 命令

如何使用 jq 对 json 数组中的每个 json 对象运行 bash 命令?到目前为止,我有以下内容:

cat credentials.json | jq -r '.[] | .user, .date, .email' | mycommand -u {user} -d {date} -e {email}

这似乎不起作用。我怎样才能将参数从 json 数组中取出放入我的命令中?

我的 json 文件如下所示:

[
   "user": "danielrvt",
   "date": "11/10/1988",
   "email": "[email protected]",
   ...
]

答案1

这是一个基于的解决方案我对类似问题的回答在 Stack Overflow 上。

#!/bin/bash
json='
[
  {
   "user": "danielrvt",
   "date": "11/10/1988",
   "email": "[email protected]"
  }, 
  {
   "user": "anotheruser",
   "date": "1/1/1970",
   "email": "[email protected]"
  }
]
'

jq -M -r '
    .[] | .user, .date, .email
' <<< "$json" | \
while read -r user; read -r date; read -r email; do
   echo "$user $date $email"
done

示例输出

danielrvt 11/10/1988 [email protected]
anotheruser 1/1/1970 [email protected]

<<< "$json"在您的情况下,您可以根据需要替换with< credentials.jsonecho "$user $date $email"with的使用,mycommand -u "$user" -d "$date" -e "$email"但这应该可以清楚地说明基本思想。

答案2

你可以使用 for 循环,例如

#!/bin/bash

JSONARRAY=$(cat credentials.json | jq -r '.[] | .user, .date, .email' | mycommand -u {user} -d {date} -e {email} | grep -v "[\|]")
for line in $JSONARRAY; do
    some command
done

相关内容