Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary Key Order in Swift 4 JSONEncoder

Is it possible to configure the Swift JSON encoder to use the sort order of the struct properties as the sort order of the dictionary keys in the JSON output? By default it uses some arbitrary (but seemingly not random) order, e.g. ...

struct Example: Codable {
  let id: Int
  let name: String
  let createdAt: Date
  let comments: [String]
}

... results in ...

"example" : {
  "id" : 1,
  "name" : "Test",
  "comments" : [
    "Comment 1",
    "Comment 2"
  ],
  "createdAt" : 549539643.25327206
}

I know that semantically the order doesn't matter, but I'd like to keep it for debugging purposes.

like image 817
lassej Avatar asked Mar 12 '26 04:03

lassej


1 Answers

JSONEncoder has outputFormatting property, you can do this,

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys

I've not tried it, please try and let me know.

like image 147
PPL Avatar answered Mar 13 '26 22:03

PPL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!