Reputation: 392
Adding a field to a tree is straightforward:
echo '{ "a": "b" }' | jq '.'
{
"a": "b"
}
echo '{ "a": "b" }' | jq '. + { c: "d" }'
{
"a": "b",
"c": "d"
}
But adding a field to an existing object does not work as was expected, by displaying only the modified subtree:
echo '{ "e": { "f": "g" } }' | jq '.'
{
"e": {
"f": "g"
}
}
echo '{ "e": { "f": "g" } }' | jq '.e + { h: "i" }'
{
"f": "g",
"h": "i"
}
Tried various workarounds but none gave what was needed :
echo '{ "e": { "f": "g" } }' | jq '. as $k | .e + { h: "i" } | $k + .'
{
"e": {
"f": "g"
},
"f": "g",
"h": "i"
}
echo '{ "e": { "f": "g" } }' | jq '. as $k | .e + { h: "i" } | $k + .e'
{
"e": {
"f": "g"
}
}
Desired output:
{
"e": {
"f": "g",
"h": "i"
}
}
Can somebody show me the errors of my ways?
Upvotes: 2
Views: 267
Reputation: 85800
If your intention is just to append an element to an object, it would be better to use +=
as
jq '.e += { "h" : "i" }'
In action,
echo '{ "e": { "f": "g" } }' | jq '.e += { "h" : "i" }'
{
"e": {
"f": "g",
"h": "i"
}
}
Upvotes: 4