3

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"
    }
 ]

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

What if it is like this { "data": [ { "id":"1", "name":"Blue" }, { "id":"2", "name":"Red" }]}
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.
It just outputs it to the console but it doesn't write it to the file?
@somethingyouwant jq won't edit the file in place; you'll need to redirect to a second file and then replace the original.
... or use sponge (or equivalent -- see especially stackoverflow.com/questions/6604852/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.