Quantcast
Channel: Active questions tagged jq - Stack Overflow
Viewing all articles
Browse latest Browse all 657

Apply jq functions conditionally to matching and non-matching JSON subtrees

$
0
0

I want to apply one function to all descendants of a particular node in a tree, and a different function to all other nodes, in the following way:

if path_matches(.deep.path.matching) then apply_function_matching else apply_function_other end

To make writing and reading more comfortable I use yaml, but I'm looking for the jq solution.

As a practical example for applying particular functions to matching and non-matching subtrees I'd like to start with:

if path_matches(.deep.path.matching) then change_x else delete_y end

With this input ...

deep:  path:    matching:      m:        x: change it        y: don't touch      n:        nn:          x: change it          y: don't touch    other_a:      a:        x: don't touch        y: delete it    other_b:      b:        bb:          x: don't touch          y: delete itanother_other:  x: don't touch  y: delete it

... the output should be:

deep:  path:    matching:      m:        x: changed        y: don't touch # not touched      n:        nn:          x: changed          y: don't touch # not touched    other_a:      a:        x: don't touch # not touched        # y deleted    other_b:      b:        bb:          x: don't touch # not touched          # y deletedanother_other:  x: don't touch # not touched  # y deleted

Maybe there are solutions that are quite compact, maybe there are solutions that are performant because they avoid traversing the tree twice, or maybe there are even solutions that achieve both.

I'm interested in all of them, but so far, I haven't found any.


Viewing all articles
Browse latest Browse all 657

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>