I have a bunch of JSON objects that I’d like to print to the screen.
I’d like to sort the keys to make them easier to read.
This python code does what I want:
I tried using json.Unmarshal and json.Marshal but it filters out lowercase keys.
It also leaves no spaces in the output, which is a little hard to read.
I don’t know the format of the messages ahead of time.
I only know that they will be JSON objects.
I had a mistake in the original question.
json.Unmarshal and json.Marshal do not filter out lowercase keys.
It puts lowercase stuff at the end so I didn’t see it in the output.
So this code does the alphabetical ordering right.
To pretty print your JSON instead of Marshal function you can simply use MarshalIndent. About reordering, yeah, you can imagine a function to do this but keep in mind that JSON is a format for data exchange and the order of elements is not guaranteed and should not mater.
The JSON Data Interchange Standard definition at json.org specifies that “An object is an unordered [emphasis mine] set of name/value pairs”, whereas an array is an “ordered collection of values”. In other words, by definition the order of the key/value pairs within JSON objects simply does not, and should not, matter .