Skip to content

Instantly share code, notes, and snippets.

@ohnit
Last active May 6, 2020 23:59
Show Gist options
  • Save ohnit/821fdc31c43de1dd29b4d938d12bee7f to your computer and use it in GitHub Desktop.
Save ohnit/821fdc31c43de1dd29b4d938d12bee7f to your computer and use it in GitHub Desktop.
# Recurses a json object and creates a list of breadcrumbs strings
#
# For example:
# jq '.stuff | breadcrumbs(.children?; .name)'
# This will recurse in every object containg a "children" key and for each object
# found, it will add its "name" field to the breadcrumb trail
#
# Parameters:
# - get_children: function which given an object, should return array of its children
# - get_name: function which given an object, should return a string to be added to the breadcrumb trail
# - $joiner: (Optional) string in between breadcrumbs. Default is " > "
# - $prepend: (Optional) string that will be at the beginning of every breadcrumb trail
def breadcrumbs(get_children; get_name; $joiner; $prepend):
(if type == "object" then
$prepend + get_name as $name |
get_children as $children |
(if ($children | length) > 0 then
$name, ($children | breadcrumbs(get_children; get_name; $joiner; $name + $joiner))
else
$name
end)
elif type == "array" then
.[] | breadcrumbs(get_children; get_name; $joiner; $prepend)
else
empty
end);
def breadcrumbs(get_children; get_name; $joiner): breadcrumbs(get_children; get_name; $joiner; "");
def breadcrumbs(get_children; get_name): breadcrumbs(get_children; get_name; " > "; "");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment