[英]Separate "Curl POST's" with data from json file - Windows CMD Shell
我正在处理 API 连接,我正在接收包含多个对象的 JSON 数据集,我正在尝试将其传递给下一个系统。
JSON 数据集具有以下信息 (OUTPUT.JSON):
[
{
"initials": "V.",
"firstName": "Victor",
"lastNamePrefix": " ",
"lastName": "Rutherford",
"employerReferenceId": "0258741",
"jobDescription": "Rental"
},
{
"initials": "P.",
"firstName": "Pippa",
"lastNamePrefix": " ",
"lastName": "Lewis",
"employerReferenceId": "98765431",
"jobDescription": "Rental"
},
{
"initials": "S.",
"firstName": "Stephanie",
"lastNamePrefix": " ",
"lastName": "Reid",
"employerReferenceId": "123456789",
"jobDescription": "Rental"
}
]
我尝试做的 API 帖子必须是 JSON 数据文件中每个对象(人)的单独帖子。 这是因为帖子必须在每个帖子的 URL 中包含 EMPLOYERREFEREBCEID 的引用编号,但帖子还需要在 JSON 文件中仅包含属于该 EMPLOYERREFEREBCEID 的数据部分。
curl -X POST "https://website.eu/test-Company/api2/external-employees/[EMPLOYERREFEREBCEID]" -H "accept: application/json" -H "Authorization: Token {TOKEN}" -H "Content-Type: application/json" -d "@output.json"
我确实找到了一篇适用于 JQ 和 Bash 的旧帖子,但由于我运行的是 Windows Server 2016,这将具有挑战性
for (( i = 0 ; i < ${#id[@]} ; i++ ))
do
POST REST API
done
这花了我很长时间但是..我有第一部分工作。
解决了!
for i in $(cat "c:\Test\output.json" | jq -r .[].employerReferenceId); do
在这部分启动 Curl 命令之后,它在数据部分之前也可以正常工作,这就是我现在卡住的地方。
curl -X POST "https://website.eu/test-Company/api2/external-employees/$i" -H "accept: application/json" -H "Authorization: Token {TOKEN}" -H "Content-Type: application/json" -d "EXAMPLE: $initials:value $firstName:value $lastNamePrefix:value $lastName:value $employerReferenceId:value $jobDescription:value"
问题:如何引用 curl 命令数据部分中 $i 中属于 person 的相应值。
您可能对 JSON-parser xidel 感兴趣,对于它来说这是一项相对容易的任务。
不需要 FOR 循环。 一个xidel
调用就足够了。
xidel -s "OUTPUT.JSON" -e ^"^
for $x in $json() return^
x:request({^
'headers':(^
'accept: application/json',^
'Authorization: Token %TOKEN%',^
'Content-Type: application/json'^
),^
'post':serialize($x,{'method':'json'}),^
'url':'https://website.eu/test-Company/api2/external-employees/'^|^|$x/employerReferenceId^
})/json^
"
这是cmd美化版本(带有必要的转义字符)。
或者缩小版:
xidel -s "OUTPUT.JSON" -e "for $x in $json() return x:request({'headers':('accept: application/json','Authorization: Token %TOKEN%','Content-Type: application/json'),'post':serialize($x,{'method':'json'}),'url':'https://website.eu/test-Company/api2/external-employees/'||$x/employerReferenceId})"
对于每个 JSON 对象(人) x:request()
发送一个 POST 请求。 如您所见,它接受选项作为 JSON 对象。
%TOKEN%
变量){"initials":"V.","firstName":"Victor","lastNamePrefix":" ","lastName":"Rutherford","employerReferenceId":"0258741","jobDescription":"Rental"}
employerReferenceId
属性值的基本 url。 例如,第一个 JSON 对象的 url: https://website.eu/test-Company/api2/external-employees/0258741
://website.eu/test-Company/api2/external-employees/0258741。x:request()
的输出也是一个 JSON 对象。 如果此 url/api 也返回 JSON,那么您可以通过选择json
-属性来解析它: x:request(...)/json
。 如果不是,则x:request(...)/raw
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.