我有一个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数组以查找数组中的最后一个值并在此之后追加或插入新值?
答案 0 :(得分:1)
如果你的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\": 1\n}]|g" itemlist.json
注意:itemlist.json文件包含JSON代码。
答案 1 :(得分:0)
您可以使用jq来解析shell中的json。 jq可以有选择地将字符串附加到json文件。
此代码将实现您的目标:
cat your.json | jq '.itemPosition |= . + [{"posId":"item_1_5","rowPos": 2,"columnPos": 1}]'
编辑:这仅适用于json文件的第1行到第21行,该行从第22行打开。