我向 API 发出curl 请求并使用 jq 获取 json 返回。
结果
{
"errors": [],
"metadata": {
"clientTransactionId": "",
"serverTransactionId": "20190318164551347"
},
"responses": [
{
"comment": "",
"keyData": {
"algorithm": 13,
"flags": 257,
"protocol": 3,
"publicKey": "a1"
},
"keyTag": 28430
},
{
"comment": "",
"keyData": {
"algorithm": 13,
"flags": 257,
"protocol": 3,
"publicKey": "a4"
},
"keyTag": 28430
},
{
"comment": "",
"keyData": {
"algorithm": 13,
"flags": 257,
"protocol": 3,
"publicKey": "fa4"
},
"keyTag": 33212
}
],
"status": "success",
"warnings": []
}
现在我想要一个循环来发出第二个 api 请求,其中包含 keyData 的四个值
但我怎样才能做到呢?我找了半天也没找到。
我的请求:
curl -v -X POST --data '{
"authToken": ".......",
"clientTransactionId": "",
}' https:/domain.tld/api/v1/json/keysList | jq .
使用 jq '.responses[]' 我有一个“数组”,但我找不到带有我的值的循环的解决方案。
答案1
您可以用来jq
检索“keyData”对象,然后将其通过管道传输到while read
:
jq -c '.responses[].keyData' file.json
{"algorithm":13,"flags":257,"protocol":3,"publicKey":"a1"}
{"algorithm":13,"flags":257,"protocol":3,"publicKey":"a4"}
{"algorithm":13,"flags":257,"protocol":3,"publicKey":"fa4"}
从那里开始:
jq -c '.responses[].keyData' file.json |
while read keydata; do curl --data "'$keydata'" http://example.com/service ; done
输入原始curl
命令,整个管道将如下所示:
curl -v -X POST --data '{ "authToken": ".......", "clientTransactionId": "",}' https:/domain.tld/api/v1/json/keysList |
jq -c '.responses[].keyData' file.json |
while read keydata; do curl --data "'$keydata'" http://example.com/service ; done
curl
请记住在执行之前用实际的 URL、选项等修改第二个命令。如果有必要,您可以在命令前添加echo
/语句,以查看您的请求是什么样的。printf
curl
答案2
或者,您可以使用 UNIX 实用程序jtc
遍历 keyData:
bash $ <file.json jtc -w'[responses][:][keyData]' -r
{ "algorithm": 13, "flags": 257, "protocol": 3, "publicKey": "a1" }
{ "algorithm": 13, "flags": 257, "protocol": 3, "publicKey": "a4" }
{ "algorithm": 13, "flags": 257, "protocol": 3, "publicKey": "fa4" }
bash $
并将其喂入卷曲:
bash $ <file.json jtc -w'[responses][:][keyData]' -r | while read keydata; do curl --data "'$keydata'" http://example.com/service ; done