如何使用重复字段将动态值传递给JSON [英] How to pass dynamic values to JSON with duplicate fields

查看:48
本文介绍了如何使用重复字段将动态值传递给JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,必须批量发送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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆