Search code examples
jsonswiftnsjsonserialization

Write a prettyPrinted JSON object with sorted keys in Swift


We often want to use JSON for human readability. As such, it is common to ask to sort the JSON keys alphabetically (or alphanumerically) in Go, in .NET, in Python, in Java, ...

But how to output a JSON with JSON keys sorted alphabetically in Swift?

PrettyPrinted output is easy:

JSONSerialization.writeJSONObject(jsonObject, to: outputStream, options: [.prettyPrinted], error: nil)

Yet the keys are not alphabetically sorted for human readability. They are likely in the order given by NSDictionary.keyEnumerator(). But sadly, we can't subclass Dictionary, NSDictionary or CFDictionary in Swift, so we can't override the behavior of keys order.

[edit: actually, we can subclass NSDictionary, see one of my answers below]


Solution

  • For iOS 11+ and macOS High Sierra (10.13+), a new option .sortedKeys solves the problem easily:

    JSONSerialization.writeJSONObject(jsonObject, to: outputStream, options: [.sortedKeys, .prettyPrinted], error: nil)
    

    Thank you Hamish for the hint.