Last active
June 3, 2024 15:24
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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