我希望修改我的JSON并添加更多的字段
当前的JSON:
{
"cubes": [
{
"no": 1,
"plant_number": "1050-0"
},
{
"no": 2,
"plant_number": "2050-0"
},
{
"no": 3,
"plant_number": "3050-0"
}
]
}
我希望添加新字段并且输出应如下所示:
期望输出:
{
"no": 1,
"plant_number": "1050-0",
"1050-0":"1.1.1.1"
}
{
"no": 2,
"plant_number": "2050-0",
"2050-0":"2.2.2.2"
}
{
"no": 3,
"plant_number": "3050-0",
"3050-0":"3.3.3.3"
}
这些IP应该通过bash提取,因此我编写了以下脚本:
第一次尝试: 我可以像下面这样添加静态IP:
jq '.cubes[]| {no,plant_number} | . + {(.plant_number): "0.0.0.0"} ' my.json
它的结果如下 JSON
{
"no": 1,
"plant_number": "1050-0",
"1050-0","0.0.0.0"
}
{
"no": 2,
"plant_number": "2050-0",
"2050-0":"0.0.0.0"
}
{
"no": 3,
"plant_number": "3050-0",
"3050-0":"0.0.0.0"
}
第二次尝试:
# Here for sake of simplicity declaration is like this otherwise its function which return array
declare -a ips=('1.1.1.1' '2.2.2.2' '3.3.3.3');
jq '.cubes[]| {no,plant_number} | . + {(.plant_number): $ips} ' my.json
它出现了错误。
jq: 1 compile error
第三次尝试:
declare -a ips=('1.1.1.1' '2.2.2.2' '3.3.3.3');
jq --arg ips $ips '.cubes[]| {no,plant_number} | . + {(.plant_number): $ips} ' my.json
这会导致以下结果。
{
"no": 1,
"plant_number": "1050-0",
"1050-0": "1.1.1.1 2.2.2.2 3.3.3.3"
}
{
"no": 2,
"plant_number": "2050-0",
"2050-0": "1.1.1.1 2.2.2.2 3.3.3.3"
}
{
"no": 3,
"plant_number": "3050-0",
"3050-0": "1.1.1.1 2.2.2.2 3.3.3.3"
}
我如何动态地给数组分配值?
{"no": 1, "plant_number": "1050-0", "1050-0": "1.1.1.1"}
这样的格式? - chepner