在两个JSON文件上进行Bash双循环以执行命令



我为json文件中的每个对象运行这个curl命令

jq -c '.[]' json.json |
while IFS= read -r fragment; do
curl -X POST 
-H "X-Primotexto-ApiKey: 784155c6ad9d0a4d1ffdb67466" 
-H "Content-Type: application/json" 
-d "$fragment" 
https://api.primotexto.com/v2/notification/messages/send;
done

json文件:

[
{
"number": "+336000287407",
"message": "Bonjour :)nNou corps.nn",
"sender": "BEinstitute",
"date": 1539367199999
},
{
"number": "+336000287407",
"message": "J'inspire, ps aujourd'hui de faire votre pratique quotidienne.",
"sender": "BEinstitute",
"date": 1539421199999
},
{
"number": "+336000287407",
"message": "En devenant re votre pratique quotidienne.",
"sender": "BEinstitute",
"date": 1539507599999
},
{
"number": "+336000287407",
"message": "Ralentir le flot ",
"sender": "BEinstitute",
"date": 1539593999999
},
...
]

现在我想做同样的批量处理,但对于以下文件中的每个电话号码:

[
{"number": "+33627000287407"},
{"number": "+33608000066706"},
{"number": "+31611355000094"},
{"number": "+33678490800060"},
{"number": "+33600063849305"},
{"number": "+33640003179187"},
{"number": "+33652000281148"},
{"number": "+33671000740645"},
{"number": "+33611900049942"},
{"number": "+33667100022316"},
{"number": "+33607720009877"}
]

我该怎么想?

在这里进行一点猜测:

您有一个名为numeros.json的文件,其中包含一系列数字。您希望循环浏览该数字列表,并在json.json中为每个数字找到匹配项。对于每个匹配,您都要将其提交给API。这将解释"循环中的循环",这是一种合理的方法。

您也可以通过使用xargs作为中间人将numeros.json片段管道连接到您的第二个jq来传递值::

jq '.[] | .number ' numeros.json | xargs -I {} jq -c --arg num {} '.[] | select(.number==$num)' json.json |
while IFS= read -r fragment; do
curl -X POST 
-H "X-Primotexto-ApiKey: <<<YOURAPIKEY>>>" 
-H "Content-Type: application/json" 
-d "$fragment" 
https://api.primotexto.com/v2/notification/messages/send;
done

您在json.json上的原始jq在这里变得有点复杂,因为我们需要使用--args标志来捕获数字,并使用jq中的select()来进行搜索。

不过,你完全可以像在答案中那样使用for循环,而不是xargs,但我建议切换第二个jq,因为我在这里有它来执行数字搜索。

for phone in $(jq -r '.[] | .number' numeros.json); do
jq -c --arg num "$phone" '.[] | select(.number==$num)' json.json |
while IFS= read -r fragment; do
curl -X POST 
-H "X-Primotexto-ApiKey: <<<YOURAPIKEY>>>" 
-H "Content-Type: application/json" 
-d "$fragment" 
https://api.primotexto.com/v2/notification/messages/send;
done
done

看起来这是有效的:

for phone in $(jq -r '.[] | .number' numeros.json); do
jq -c '.[]' json.json |
while IFS= read -r fragment; do
fragment=$(sed -e"s/+33677592979/$phone/;" <<< $fragment);
curl -X POST 
-H "X-Primotexto-ApiKey: 784155c6a3c99d0a4d1ffdb67466" 
-H "Content-Type: application/json" 
-d "$fragment" 
https://api.primotexto.com/v2/notification/messages/send;
done
done

最新更新