[swift-evolution] [Proposal] Foundation Swift Encoders

Ben Rimmington me at benrimmington.com
Mon Jun 12 10:32:05 CDT 2017


The new `JSONSerialization.WritingOptions.sortedKeys` option was mentioned at WWDC.

"What's New in Cocoa" [33:03 ... 33:33]
<https://developer.apple.com/videos/play/wwdc2017/207/?time=1983>

<https://developer.apple.com/documentation/foundation/jsonserialization.writingoptions>

When the `sortedKeys` option is available, can it be used **by default** in the `JSONEncoder`?

Otherwise, can the `JSONEncoder.OutputFormatting` enum have extra cases?

case compact
case compactWithSortedKeys
case prettyPrinted
case prettyPrintedWithSortedKeys

<https://developer.apple.com/documentation/foundation/jsonencoder.outputformatting>

-- Ben

> On 16 Mar 2017, at 22:47, Itai Ferber <iferber at apple.com> wrote:
> 
> The sorted order of keys is an implementation detail of PropertyListSerialization which JSONSerialization does not share.
> This would require a change in JSONSerialization, which is possible, but out of scope for this work specifically. It would have to go through review.
> 
> [FWIW, the key ordering isn’t changing at random; JSONSerialization writes keys in the order that it receives them (sorted in the order that NSDictionary stores them, based on hash). If you want this to not interfere with your Git repo (on a more immediate timescale), you can probably do something like adding a pre-commit Git hook to lint the file as needed. But I digress, this is totally off-topic.]
> 
>> On 16 Mar 2017, at 14:57, Ben Rimmington wrote:
>> 
>> Sorry, I actually meant that keys would be ordered **alphabetically** (as they are with PropertyListSerialization).
>> 
>> I'm storing output from JSONSerialization in a git repository, and when I add/remove a single key-value the entire file changes, due to keys being reordered (seemingly at random).
>> 
>> -- Ben
>> 
>>> Itai Ferber wrote:
>>> 
>>> By stable ordering, you mean dictionaries with keys being output in the order that they were encoded?
>>> Potentially, but this would require additional work as neither Swift dictionaries nor NSMutableDictionary support this (reasonable seeing as dictionaries are by definition not sorted), and the current implementation uses JSONSerialization as the concrete serializer. Certainly not impossible, though.
>>> 
>>>> On 16 Mar 2017, at 8:49, Ben Rimmington wrote:
>>>> 
>>>> <https://github.com/apple/swift-evolution/pull/640>
>>>> 
>>>> Could the `JSONEncoder.OutputFormatting.prettyPrinted` case include the **stable ordering** of keys?
>>>> 
>>>> -- Ben


More information about the swift-evolution mailing list