【发布时间】:2021-12-14 13:26:34
【问题描述】:
我想修改我的 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"
}
如何为数组动态赋值?
【问题讨论】:
-
预期输出不是有效的 JSON。
-
@choroba 对不起,我准备了 json,主要目的是添加带有 ip 的字段
-
我假设你想要,例如,
{"no": 1, "plant_number": "1050-0", "1050-0": "1.1.1.1"}? -
@chepner 正确。