JdeHaan
JdeHaan

Reputation: 392

JQ How to add a node to a complete tree

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

Answers (1)

Inian
Inian

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

Related Questions