somethingyouwant
somethingyouwant

Reputation: 161

Add a new key/value to every object in json array in file with jq

I have a json file like below. I want to add "stable": "yes" to every object in this file with jq. How can i do this?

 [
    {
        "id":"1",
        "name":"Blue"
    },
    {
        "id":"2",
        "name":"Red"
    }
 ]

I want it to be like this:

 [
    {
        "id":"1",
        "name":"Blue",
        "stable": "yes"
    },
    {
        "id":"2",
        "name":"Red",
        "stable": "yes"
    }
 ]

Upvotes: 3

Views: 4685

Answers (1)

chepner
chepner

Reputation: 531165

map and + will do this:

$ jq 'map(. + {stable: "yes"})' tmp.json
[
  {
    "id": "1",
    "name": "Blue",
    "stable": "yes"
  },
  {
    "id": "2",
    "name": "Red",
    "stable": "yes"
  }
]

Since the input is an array, the . refers to each object in that array, to which we add another object.

Note this will also override any existing stable key in each object.

Upvotes: 8

Related Questions