how.wtf

Add new element to JSON array with jq

· Thomas Taylor

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	"projects": [
 3		{
 4			"id": 1,
 5			"version": "2.3.0"
 6		},
 7		{
 8			"id": 2,
 9			"version": "1.54.0"
10		}
11	]
12}

Appending a new element to the array can be completed in two ways:

1. += []

1cat projects.json | jq '.projects += [{
2	"id": 3,
3	"version": "5.4.1"
4}]'

2. |=

1jq '.projects[.projects | length] = {
2	"id": 3,
3	"version": "5.4.1"
4}'

Output:

 1{
 2	"projects": [
 3		{
 4			"id": 1,
 5			"version": "2.3.0"
 6		},
 7		{
 8			"id": 2,
 9			"version": "1.54.0"
10		},
11		{
12			"id": 3,
13			"version": "5.4.1"
14		}
15	]
16}

Add element to existing array of strings using jq

Similarly with strings:

1echo '["id1"]' | jq '. += ["id2"]'

or

1echo '["id1"]' | jq '.[. | length] = "id2"'

Output:

1[
2	"id1",
3	"id2"
4]

#Linux  

Reply to this post by email ↪