如何使用重复字段将动态值传递给JSON [英] How to pass dynamic values to JSON with duplicate fields
问题描述
我有一个用例,必须批量发送REST请求.
I have a usecase where i have to send REST request in bulk.
JSON文件:emp.json
JSON File: emp.json
[
{
"field": {
"empID": "sapid",
"location": "India"
}
}
]
我的shell脚本:
func emp_details
{
START=1
END=1000000
CURRENT=1
while [ $END -gt $CURRENT ];
do
CURRENT=$((CURRENT+1))
cat emp.json | jq --arg new "$CURRENT" '.[].field.empID |= $new' > temp.json
cat temp.json
curl <REST Server URL with temp.json as input> "Content-Type: application/json" -d @temp.json
done
}
上面的json和脚本正在工作.我可以正确发送请求. 我正在寻找一种在触发CURL之前使用多个empID准备json文件的方法.
The above json and script is working. I am able send the request properly. I am looking for an approach to prepare the json file with mutiple empID before triggering the CURL.
例如:
[
{
"field": {
"empID": "sapid",
"location": "India",
}
},
{
"field": {
"empID": "sapid",
"location": "India",
}
},
{
"field": {
"empID": "sapid",
"location": "India",
}
}
]
但是不确定如何遍历每个empID字段并将其值替换为动态CURRENT值.
But am not sure how to traverse through each individual empID field and replace its value with dynamic CURRENT values.
非常感谢您的帮助
推荐答案
您完全不需要bash
处理.您可以使用jq
中的range()
函数创建从1到百万的数字范围,并使用reduce()
函数创建多个对象
You don't need bash
processing at all for this. You can use the range()
function in jq
to create the number range from 1 to million and create multiple objects using the reduce()
function
jq -n 'reduce range(1; 1000000) as $data (.; . + [{"field": { "empID": $data, "location": "India"}}])'
这将从1开始在设置为empID
的数组内创建一百万个对象.修改range()
中的值以自定义数字.
This creates a million objects inside the array with empID
set, starting from 1. Modify the value inside range()
to customize the numbers.
这篇关于如何使用重复字段将动态值传递给JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!