Skip to content

Instantly share code, notes, and snippets.

@rockydd
Last active January 23, 2024 22:26
Show Gist options
  • Save rockydd/b09ff6d39d1f1fa731c192eadbc0bb3a to your computer and use it in GitHub Desktop.
Save rockydd/b09ff6d39d1f1fa731c192eadbc0bb3a 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