Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify a nested object with jq

Tags:

json

jq

Given this

{
  "some": "property",
  "nested": {
    "hello": "world"
  }
}

I'd like to get this result with jq

{
  "some": "property",
  "nested": {
    "hello": "world",
    "freshly": "added"
  }
}

So how can I add the freshly added field ? I don't know how many properties are at root level (and I want to keep them all), I only know the name of the nested object (here "nested"), the name of the property I'd like to add (here "freshly") and its value.

like image 324
ValLeNain Avatar asked Jul 29 '15 07:07

ValLeNain


3 Answers

Just assign the new value to the nested object.

.nested.freshly = "added"
like image 126
Jeff Mercado Avatar answered Nov 13 '22 17:11

Jeff Mercado


Well I found out myself how to do it. If you have a better solution, you're more than welcome to give it here.

jq '.nested=(.nested + {"freshly": "added"})'
like image 41
ValLeNain Avatar answered Nov 13 '22 15:11

ValLeNain


You can also do simply

.nested += {freshly: "added"}

Then you can add multiple nested keys at once

like image 2
Kyle Barron Avatar answered Nov 13 '22 15:11

Kyle Barron