Skip to content

Instantly share code, notes, and snippets.

@madflow
Forked from rockydd/sort_script.jq
Created June 3, 2024 15:24
Show Gist options
  • Save madflow/de93297e4a9cd0f316fe9fb36e71f416 to your computer and use it in GitHub Desktop.
Save madflow/de93297e4a9cd0f316fe9fb36e71f416 to your computer and use it in GitHub Desktop.
A jq script for comprehensive sorting of JSON objects. It recursively sorts keys in objects, orders arrays by simple types, and sorts arrays of objects by 'name' or 'id'. Ideal for standardizing complex JSON structures for APIs, configurations, or data processing. Usage: jq -f sort_script.jq input.json with input.json as your target JSON file.
def recursive_sort:
if type == "object" then
to_entries
| sort_by(.key)
| map( {key: .key, value: (.value | recursive_sort)} )
| from_entries
elif type == "array" then
map( if type == "object" or type == "array" then . | recursive_sort else . end )
| if length == 0 or (first | type) != "object" then
sort
else
sort_by(if .name then .name elif .id then .id elif .displayName then .displayName else empty end)
end
else
.
end;
recursive_sort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment