Skip to content

Instantly share code, notes, and snippets.

@joar
Last active July 25, 2024 00:55
Show Gist options
  • Save joar/776b7d176196592ed5d8 to your computer and use it in GitHub Desktop.
Save joar/776b7d176196592ed5d8 to your computer and use it in GitHub Desktop.
Add a field to an object with JQ
# Add field
echo '{"hello": "world"}' | jq --arg foo bar '. + {foo: $foo}'
# {
# "hello": "world",
# "foo": "bar"
# }
# Override field value
echo '{"hello": "world"}' | jq --arg foo bar '. + {hello: $foo}'
{
"hello": "bar"
}
# {
# "hello": "bar"
# }
# Concat and add
echo '{"hello": "world"}' | jq --arg foo bar '. + {foo: ("not" + $foo)}'
# {
# "hello": "world",
# "foo": "notbar"
# }
@MaxNanasy
Copy link

@aborruso This seems to work:

jq 'to_entries | map( { (.key) : (.value + { key: .key }) }) | add'

@aborruso
Copy link

aborruso commented Jun 2, 2023

thank you @MaxNanasy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment