Say I have this JSON:
{
"lunch": {
"time": "11 am",
"food": {
"is_pizza": true
}
},
"snacks": [
{
"time": "2 pm",
"food": {
"is_pizza": true
}
},
{
"time": "3:30 pm",
"food": {
"is_pizza": true
}
}
],
"dinner": {
"time": "6 pm",
"food": {
"is_pizza": true
}
}
}
Now I want to go through and wherever I see "food"
object, add a the same key-value pair:
{
"lunch": {
"time": "11 am",
"food": {
"is_pizza": true,
"extra_cheese": true
}
},
"snacks": [
{
"time": "2 pm",
"food": {
"is_pizza": true,
"extra_cheese": true
}
},
{
"time": "3:30 pm",
"food": {
"is_pizza": true,
"extra_cheese": true
}
}
],
"dinner": {
"time": "6 pm",
"food": {
"is_pizza": true,
"extra_cheese": true
}
}
}
How can I do that in jq
?
2
Answers
here is how you can do this using the jq command line tool
Using
walk
would be one way:Demo
Using
..
would be another:Demo
If you wanted to import and add the object
{"extra_cheese": true}
from outside, use the--argjson
option: