Write a prettyPrinted JSON object with sorted keys in Swift

前端 未结 4 2159
故里飘歌
故里飘歌 2021-02-08 22:00

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, ...<

4条回答
  •  野的像风
    2021-02-08 22:34

    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.

提交回复
热议问题