Skip to content

Remove a key safely

err := doc.Remove("server.debug")

Removal is the operation where a naive editor destroys work, because it has to decide which nearby comments belonged to the key. yamldoc decides positionally — see Comment ownership for the reasoning.

What goes, and what stays

server:
  host: localhost

  # ==== TLS ====          ← blank line above: describes the SECTION, survives
  tls_cert: /etc/cert.pem
  # the port we bind to    ← directly above a key: belongs to it, goes with it
  port: 8080               # inline: goes with it
  # end of the block       ← trailing: hoisted onto the previous key, survives

Removing server.port from that document takes the two comments that describe port and leaves the other two exactly where they can still be read.

Emptiness is a value

Removing the last entry of a mapping leaves an empty mapping. The parent is never removed on your behalf:

feature:
  beta: true
other: 1
doc.Remove("feature.beta")
feature: {}
other: 1

This is deliberate. feature: {} and no feature key at all are different states, and code may legitimately require the parent to exist while it holds nothing. If you want the parent gone, remove the parent.

Removing a subtree

Removing a key removes everything beneath it:

err := doc.Remove("themes.neon")   // the whole theme, not just its first field

Errors

Remove returns ErrNotFound for a path that does not resolve. Removing something that is already absent is an error, not a no-op — silence there tends to hide a typo in a key name.