Skip to content

If you have a map of nested maps, because I have recently struggled myself with a query, I'd like to show you how you can update each of the nested maps in a consistent fashion, using multiple approaches. Your input, a single map, may resemble the following: #2358

@ShaneMellwig

Description

@ShaneMellwig

If you have a map of nested maps, because I have recently struggled myself with a query, I'd like to show you how you can update each of the nested maps in a consistent fashion, using multiple approaches. Your input, a single map, may resemble the following:

apple:
  kind: fruit
  sugar:
    min: 0.01
    max: 0.37
  edible: true
potato:
  kind: vegetable
  starch:
    min: 0.15
    max: 0.46
  edible: true
acorn:
  kind: nut

Say you want to add one or several properties to each of the maps (keyed apple, potato and acorn), the shortest expression is probably something like:

Approach 1

with_entries(.value += { "planet": "Earth", "season": "fall" })

With the above, the map expressed with { "planet": "Earth", "season": "fall" } is merged with every nested map (bound to . inside with_entries):

apple:
  kind: fruit
  sugar:
    min: 0.01
    max: 0.37
  edible: true
  planet: Earth
  season: fall
potato:
  kind: vegetable
  starch:
    min: 0.15
    max: 0.46
  edible: true
  planet: Earth
  season: fall
acorn:
  kind: nut
  planet: Earth
  season: fall

Approach 1.1

There's at least one variation on the above that produces equivalent result:

with_entries(.value.planet = "Earth" | .value.season = "fall")

Approach 1.2

The above, can be further shortened to:

with_entries(with(.value; .planet = "Earth" | .season = "fall"))

The way I understand it, with_entries is implemented in a manner where it's equivalent to:

[ to_entries.[] | with(.value; .planet = "Earth" | .season = "fall") ] | from_entries

Approach 2

with(.[]; .planet = "Earth" | .season = "fall")

Remember the importance of operator precedence rules, assuming you only wanted to add one of the properties, planet, the below snippet will not yield the expected result:

.[] | .planet = "Earth"

On the other hand, the following amendment on the above does work:

(.[] | .planet) = "Earth"

I hope all this is useful to someone.

Originally posted by @amn in #2233

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions