首页 > 解决方案 > 如何将动态值传递给具有重复字段的 JSON

问题描述

我有一个用例,我必须批量发送 REST 请求。

JSON 文件:emp.json

[
    {
        "field": {
            "empID": "sapid",
            "location": "India"
        }
    }
]

我的外壳脚本:

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 文件的方法。

例如:

[
    {
        "field": {
            "empID": "sapid",
            "location": "India",            
        }
    },
    {
        "field": {
            "empID": "sapid",
            "location": "India",            
        }
    },
    {
        "field": {
            "empID": "sapid",
            "location": "India",            
        }
    }
]

但我不确定如何遍历每个单独的 empID 字段并将其值替换为动态 CURRENT 值。

任何帮助深表感谢

标签: jsonbashshelljq

解决方案


您正在寻找range内置的。

.[] | [.field.empID = range(1;1000000)]

jqplay.org 上的演示


推荐阅读