Skip to content

Instantly share code, notes, and snippets.

@levi-nz
Created May 18, 2023 15:53
Show Gist options
  • Save levi-nz/fec32516deafcb6817796cde20fc4d7b to your computer and use it in GitHub Desktop.
Save levi-nz/fec32516deafcb6817796cde20fc4d7b to your computer and use it in GitHub Desktop.
JSON key ordering in objects
import json
class OrderedObjectDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, obj):
return {key: value for key, value in sorted(obj.items())}
# Fill input.json with your JSON input and run:
# python3 reorder_payload.py
# (or run in your IDE)
#
# Output will save to output.json.
if __name__ == "__main__":
with open("input.json") as f:
ordered_json = json.load(f, cls=OrderedObjectDecoder)
with open("output.json", "w") as f:
json.dump(ordered_json, f, indent=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment