我有一个json,我需要从中提取一个部分并将新值附加/插入到现有数组中。我的代码如下,
{
"itemId": "item_1",
"itemName": "item 1",
"itemPosition": [{
"posId": "item_1_1",
"rowPos": 0,
"columnPos": 0
}, {
"posId": "item_1_2",
"rowPos": 0,
"columnPos": 1
}, {
"posId": "item_1_3",
"rowPos": 1,
"columnPos": 0
}, {
"posId": "item_1_4",
"rowPos": 1,
"columnPos": 1
}]
}, {
"itemId": "item_2",
"itemName": "item 2",
"itemPosition": [{
"posId": "item_2_1",
"rowPos": 0,
"columnPos": 0
}, {
"posId": "item_2_2",
"rowPos": 0,
"columnPos": 1
}, {
"posId": "item_2_3",
"rowPos": 1,
"columnPos": 0
}, {
"posId": "item_2_4",
"rowPos": 1,
"columnPos": 1
}]
}
在这个 JSON 中,我需要在项目 ID "item_1"下的 itemPosition 中添加一个新值,例如
{
"posId": "item_1_5",
"rowPos": 2,
"columnPos": 1
}
我使用以下命令使用字符串搜索提取 json,例如
cat sample.json | nl | sed -n '/"item_1"/,/"item_2"/p'
输出为 :
2 "itemId": "item_1",
3 "itemName": "item 1",
4 "itemPosition": [{
5 "posId": "item_1_1",
6 "rowPos": 0,
7 "columnPos": 0
8 }, {
9 "posId": "item_1_2",
10 "rowPos": 0,
11 "columnPos": 1
12 }, {
13 "posId": "item_1_3",
14 "rowPos": 1,
15 "columnPos": 0
16 }, {
17 "posId": "item_1_4",
18 "rowPos": 1,
19 "columnPos": 1
20 }]
21 }, {
22 "itemId": "item_2",
问题是我应该如何遍历 itemPosition 数组以查找数组中的最后一个值,并在该值之后附加或插入一个新值?
的 Linux 盒子里没有安装 JQ 或任何解析器,你可以使用以下代码。 它应该适合您的要求。 请检查。
line_to_be_replaced=`cat itemlist.json | nl | sed -n '/"item_1"/,/"item_2"/p' | grep -in "}]" | awk '{print $2}'`
sed -i "${line_to_be_replaced} s|.*|}, {n"posId": "item_1_5",n"rowPos": 2,n"columnPos": 1n}]|g" itemlist.json
注意:itemlist.json 文件包含 JSON 代码。
您可以使用 jq 在 shell 中解析 json。 jq 可以有选择地将字符串附加到 JSON 文件。
此代码将实现您尝试执行的操作:
cat your.json | jq '.itemPosition |= . + [{"posId":"item_1_5","rowPos": 2,"columnPos": 1}]'
编辑:这仅适用于从第 22 行开始断开的 JSON 文件的第 1 行到第 21 行。