I have a json, from which I need to extract a part and append/insert a new value into the existing array. My code is as follows,
{
"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
}]
}
in this json i need to add a new value in itemPosition under the item id "item_1" like
{
"posId": "item_1_5",
"rowPos": 2,
"columnPos": 1
}
I used following command to extract the json using string search like
cat sample.json | nl | sed -n '/"item_1"/,/"item_2"/p'
output is :
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",
Question is how should I traverse into itemPosition array to find the last value in the array and append or insert a new value after that?
cat your.json | python -m json.toolreturnsExtra data: line 21 column 2 - line 41 column 2 (char 338 - 666)