Last active
March 18, 2024 16:06
-
-
Save joar/776b7d176196592ed5d8 to your computer and use it in GitHub Desktop.
Add a field to an object with JQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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" | |
# } |
A few more examples to insert json:
echo '{"hello": "world"}' | jq --argjson json '{"foo": "bar"}' '. + {foo: $json}'
{
"hello": "world",
"foo": {
"foo": "bar"
}
}
and same but with files
cat template.json | jq --argjson json "`<snippet.json`" '. + {foo: $json}'
To add a key to a nested object, you can use
.key +=
:echo '{"hello": {"value": "world"}}' | jq '.hello += {other_key: "new_val"}'
{ "hello": { "value": "world", "other_key": "new_val" } }
If you are only adding or modifying a single value, there is no need to merge JSON. Same output as above:
echo '{"hello": {"value": "world"}}' | jq '.hello.other_key = "new_val"'
Example for adding an element to an array:
$ echo '[ {"data1":"A"}, {"data2":"B"} ]' | jq --arg val True '.[] += {uppercase: $val}'
[
{
"data1": "A",
"uppercase": "True"
},
{
"data2": "B",
"uppercase": "True"
}
]
Hi,
I have this input
{
"a":{"fieldA":2,"fieldB":"foo"},
"b":{"fieldA":2,"fieldB":"foo"}
}
And I would like for each key, to add its value inside the related json object
{
"a":{"fieldA":2,"fieldB":"foo","key":"a"},
"b":{"fieldA":2,"fieldB":"foo","key":"b"}
}
If I run this
<input.json jq '[.|keys[] as $key | .[] + {key: $key}]'
I obtain something similar, but I have the cartesian product
[
{
"fieldA": 2,
"fieldB": "foo",
"key": "a"
},
{
"fieldA": 2,
"fieldB": "foo",
"key": "a"
},
{
"fieldA": 2,
"fieldB": "foo",
"key": "b"
},
{
"fieldA": 2,
"fieldB": "foo",
"key": "b"
}
]
How to avoid it?
Thank you
@aborruso This seems to work:
jq 'to_entries | map( { (.key) : (.value + { key: .key }) }) | add'
thank you @MaxNanasy
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this! used it to quickly enable experimental features in docker, so I can start playing with buildx inside a VM:
Ref: https://docs.docker.com/buildx/working-with-buildx/#build-multi-platform-images