Write a prettyPrinted JSON object with sorted keys in Swift

前端 未结 4 2156
故里飘歌
故里飘歌 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:42

    Solution for iOS 7+, macOS 10.9+ (OS X Mavericks and up).

    A solution is to subclass NSDictionary in Objective-C, then use the subclass from a framework (for Application) or static library (for Command Line Tool).

    For this demonstration, I will use nicklockwood/OrderedDictionary (700+ lines of code) instead of doing it from scratch, but there may be untested alternatives like quinntaylor/CHOrderedDictionary or rhodgkins/RDHOrderedDictionary. To integrate it as a Framework, add this dependency in your PodFile:

    pod 'OrderedDictionary', '~> 1.4'
    

    Then we will order the keys of our object:

    import OrderedDictionary
    
    let orderedJson = MutableOrderedDictionary()
    jsonObject.sorted { $0.0.compare($1.0, options: [.forcedOrdering, .caseInsensitive]) == .orderedAscending }
              .forEach { orderedJson.setObject($0.value, forKey: $0.key) }
    

    (note: setObject(_,forKey:) is specific to MutableOrderedDictionary)
    And finally we can write it prettyPrinted:

    _ = JSONSerialization.writeJSONObject(orderedJson, to: outputJSON, options: [.prettyPrinted], error: nil)
    

    But be careful: you need to subclass and sort all subdictionaries of your JSON object.

提交回复
热议问题