Adding a new element to an existing JSON array can be completed using jq
.
Add element to existing array of objects using jq
This is a generic projects.json
file:
1
2
3
4
5
6
7
8
9
10
11
12
| {
"projects": [
{
"id": 1,
"version": "2.3.0"
},
{
"id": 2,
"version": "1.54.0"
}
]
}
|
Appending a new element to the array can be completed in two ways:
1. += []
1
2
3
4
| cat projects.json | jq '.projects += [{
"id": 3,
"version": "5.4.1"
}]'
|
2. |=
1
2
3
4
| jq '.projects[.projects | length] = {
"id": 3,
"version": "5.4.1"
}'
|
Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| {
"projects": [
{
"id": 1,
"version": "2.3.0"
},
{
"id": 2,
"version": "1.54.0"
},
{
"id": 3,
"version": "5.4.1"
}
]
}
|
Add element to existing array of strings using jq
Similarly with strings:
1
| echo '["id1"]' | jq '. += ["id2"]'
|
or
1
| echo '["id1"]' | jq '.[. | length] = "id2"'
|
Output: