Search code examples
yq

How to move root node under new node in yq?


In mikefarah/yq, how do you move the root node under a new parent node? For example,

yq '...' <<<'hello: world'

Gives the following output:

$ yq '...' <<<'hello: world'
cat:
  dog:
    hello: world

As a workaround, I assign the root node to a new tmp root node, then filter out—see below. But I wonder if there is a better way.

$ yq '. as $root | .tmp.cat.dog = $root | .tmp' <<<'hello: world'
cat:
  dog:
    hello: world

Solution

  • how do you move the root node under a new parent node?

    You can simply create the new document with a reference to the input context . (see Wrap (prefix) existing object in the manual):

    yq '{"cat":{"dog":.}}' <<< 'hello: world'
    

    If you want to preserve the .cat.dog path expression notation, you can start off with an empty object {} instead of using a placeholder like .tmp:

    yq '. as $root | {} | .cat.dog = $root' <<< 'hello: world'
    

    Output:

    cat:
      dog:
        hello: world