1

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"
    }
 ]
somethingyouwant
  • 141
  • 2
  • 10

1 Answers1

4

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • What if it is like this { "data": [ { "id":"1", "name":"Blue" }, { "id":"2", "name":"Red" }]} – somethingyouwant Oct 11 '18 at 15:01
  • 1
    Modify the filter to update the `data` key of the top-level object: `.data |= map(...)`. The `|=` operator pipes the left-hand side through the right-hand side, updating the original input in the process. – chepner Oct 11 '18 at 15:19
  • It just outputs it to the console but it doesn't write it to the file? – somethingyouwant Oct 11 '18 at 16:33
  • @somethingyouwant `jq` won't edit the file in place; you'll need to redirect to a second file and then replace the original. – chepner Oct 11 '18 at 17:11
  • 1
    ... or use `sponge` (or equivalent -- see especially https://stackoverflow.com/questions/6604852/powershell-equivalent-to-sponge-in-moreutils) – peak Oct 11 '18 at 18:08