Entries
Similar to the same named functions in jq these functions convert to/from an object and an array of key-value pairs. This is most useful for performing operations on keys of maps.
Use with_entries(op) as a syntactic sugar for doing to_entries | op | from_entries.
to_entries Map
Given a sample.yml file of:
a: 1
b: 2then
yq 'to_entries' sample.ymlwill output
- key: a
  value: 1
- key: b
  value: 2to_entries Array
Given a sample.yml file of:
- a
- bthen
yq 'to_entries' sample.ymlwill output
- key: 0
  value: a
- key: 1
  value: bto_entries null
Given a sample.yml file of:
nullthen
yq 'to_entries' sample.ymlwill output
from_entries map
Given a sample.yml file of:
a: 1
b: 2then
yq 'to_entries | from_entries' sample.ymlwill output
a: 1
b: 2from_entries with numeric key indices
from_entries always creates a map, even for numeric keys
Given a sample.yml file of:
- a
- bthen
yq 'to_entries | from_entries' sample.ymlwill output
0: a
1: bUse with_entries to update keys
Given a sample.yml file of:
a: 1
b: 2then
yq 'with_entries(.key |= "KEY_" + .)' sample.ymlwill output
KEY_a: 1
KEY_b: 2Use with_entries to update keys recursively
We use (.. | select(tag="map")) to find all the maps in the doc, then |= to update each one of those maps. In the update, with_entries is used.
Given a sample.yml file of:
a: 1
b:
  b_a: nested
  b_b: thingthen
yq '(.. | select(tag=="!!map")) |= with_entries(.key |= "KEY_" + .)' sample.ymlwill output
KEY_a: 1
KEY_b:
  KEY_b_a: nested
  KEY_b_b: thingCustom sort map keys
Use to_entries to convert to an array of key/value pairs, sort the array using sort/sort_by/etc, and convert it back.
Given a sample.yml file of:
a: 1
c: 3
b: 2then
yq 'to_entries | sort_by(.key) | reverse | from_entries' sample.ymlwill output
c: 3
b: 2
a: 1Use with_entries to filter the map
Given a sample.yml file of:
a:
  b: bird
c:
  d: dogthen
yq 'with_entries(select(.value | has("b")))' sample.ymlwill output
a:
  b: birdLast updated
Was this helpful?