json - 在 bash 脚本中循环 JSON
问题描述
目标是根据从 API 检索到的 JSON 格式的数据创建环境变量。
例子:
ValueA=pass1
ValueB=pass2
...
result=$(curl -l -k -X GET -H "Content-Type: application/json" -H "Authorization: bearer ${token}" "$PasswordServerURL/api/v6/rest/folders/$IdFolder" | jq -r '.Credentials')
通过运行命令,我得到$result的以下输出:
[
{
"CustomUserFields":{
},
"CustomApplicationFields":{
},
"Attachments":[
],
"Tags":[
],
"HasModifyEntriesAccess":true,
"HasViewEntryContentsAccess":true,
"HasViewEntryPasswordAccess":true,
"CommentPrompts":{
"AskForCommentOnViewPassword":false,
"AskForCommentOnViewOffline":false,
"AskForCommentOnModifyEntries":false,
"AskForCommentOnMoveEntries":false,
"AskForCommentOnMoveFolders":false,
"AskForCommentOnModifyFolders":false
},
"Id":"34307337-6b90-4b6f-bc1d-3dba50fa9cbd",
"Name":"valueA",
"Username":"valueA",
"Password":null,
"Url":"",
"Notes":"",
"GroupId":"cd52d662-0771-4eb6-9309-d12aff60b6bb",
"Created":"2021-06-16T00:07:44+02:00",
"Modified":"2021-06-16T18:52:00+02:00",
"Expires":null
},
{
"CustomUserFields":{
},
"CustomApplicationFields":{
},
"Attachments":[
],
"Tags":[
],
"HasModifyEntriesAccess":true,
"HasViewEntryContentsAccess":true,
"HasViewEntryPasswordAccess":true,
"CommentPrompts":{
"AskForCommentOnViewPassword":false,
"AskForCommentOnViewOffline":false,
"AskForCommentOnModifyEntries":false,
"AskForCommentOnMoveEntries":false,
"AskForCommentOnMoveFolders":false,
"AskForCommentOnModifyFolders":false
},
"Id":"c92729e3-1325-4725-ae8e-baba4a0d31b5",
"Name":"ValueB",
"Username":"ValueB",
"Password":null,
"Url":"",
"Notes":"",
"GroupId":"cd52d662-0771-4eb6-9309-d12aff60b6bb",
"Created":"2021-06-16T00:08:05+02:00",
"Modified":"2021-06-16T18:51:48+02:00",
"Expires":null
}
]
为了获取密码,我得到了$result的 id,并使用了另一个curl的循环:
ListeId=$(echo "${result}" | jq -r ".[] | .Id")
for CredId in $ListeId
do
secret=$(curl -l -k -X GET -H "Content-Type: application/json" -H "Authorization: ${token}" "$PasswordServerURL/api/v6/rest/credential/$CredId/password")
done
我得到“pass1”和“pass2”
如何将每个用户名(值 A、值 B ...)与其密码匹配?第二个问题是如何将它们导出为 bash 脚本中的环境变量?谢谢
解决方案
我不清楚“将它们导出为环境变量”的确切含义,但您可以从查看代码的以下变体开始,尽管我实际上并不推荐export "$Username=$secret"
:
while read -r CredId Username
do
secret=$(curl -l -k -X GET -H "Content-Type: application/json" -H "Authorization: ${token}" "$PasswordServerURL/api/v6/rest/credential/$CredId/password")
export "$Username=$secret"
echo "Username:secret=$Username:$secret"
done < <(jq -r '.[] | "\(.Id) \(.Username)"' < so-loop-over-json.json)
以上当然取决于“Credid”是单个令牌的假设。如果对此有任何疑问,很容易相应地调整上述内容。
感谢@GlennJackman。
推荐阅读
- javascript - React - 通过单击更改样式组件
- python - 如何使用 Scrapy 从经济时代检索动态链接
- apache - 配置 Apache httpd 以将子域映射到子目录
- javascript - cpu密集型功能延迟消息
- javascript - 如何将 Javascript 中的变量初始化为 INFINITE 值?
- c# - Entity Framework Core Database 首先不渲染存储过程的模型?
- flutter - 如何在 url_launcher 中打开 Gmail 应用程序(不创建电子邮件只是打开收件箱)?
- flutter - 如何像这样在颤动中做数据
- kubernetes - 在不同主机上使用复制容器安排作业
- javascript - d3 为选择获取数据绑定有效,但是当我迭代选择时,它不起作用