Created
May 18, 2023 15:53
-
-
Save leafypout/fec32516deafcb6817796cde20fc4d7b to your computer and use it in GitHub Desktop.
JSON key ordering in objects
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
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