jq - Append JSON

by
Jeremy Canfield |
Updated: November 25 2024
| jq articles
Let's say you have a file named my.json that contains the following.
{}
Here is how you could append a JSON key and value. This will not overwrite my.json, but instead will just store the result in the stdout variable.
~]$ stdout=$(cat my.json | jq '.foo += "bar"'); echo $stdout
{ "foo": "bar" }
You can append nested keys.
~]$ stdout=$(cat my.json | jq '.greeting.hello += "world"'); echo $stdout
{ "greeting": { "hello": "world" } }
Use double quotes if keys or values contain whitespace.
~]$ stdout=$(cat my.json | jq '.greeting."foo bar" += "hello world"'); echo $stdout
{ "greeting": { "foo bar": "hello world" } }
Here is how you could append a list.
~]$ stdout=$(cat my.json | jq '.greeting += ["hello world"]'); echo $stdout
{ "greeting": [ "hello world" ] }
Redirection can be used to overwrite my.json with the revised JSON.
stdout=$(cat my.json | jq '.data += ["line two"]'); echo $stdout > my.json
You can pipe together multiple statements.
]$ echo {} | jq '.data += [{"foo":"hello"}]' | jq '.data += [{"bar":"world"}]'
{
"data": [
{
"foo": "hello"
},
{
"bar": "world"
}
]
}
Or like this.
]$ echo {\"data\":{\"greeting\":[{\"foo\":\"hello\"}]}} | jq '.data.greeting += [{"foo":"world"}]'
{
"data": {
"greeting": [
{
"foo": "hello"
},
{
"foo": "world"
}
]
}
}
You can escape double quotes so that you can include variables.
~]$ foo=world
~]$ echo {} | jq ".data += [{\"hello\": \"$foo\"}]"
{
"data": [
{
"hello": "world"
}
]
}
Did you find this article helpful?
If so, consider buying me a coffee over at