JSONEncoder and JSONDecoder should support top-level fragments

Originator:sindresorhus
Number:rdar://43035278 Date Originated:08-Aug-2018 01:10 PM
Status:Open (Duplicate of 38549586) Resolved:
Product:macOS + SDK Product Version:macOS 10.13
Classification:Other Bug Reproducible:Always
 
Summary:
The [RFC 7159 JSON spec][1] allows top-level fragments, like `99`, but JSONEncoder/JSONDecoder does not support this. Top-level fragments can be useful to save single values to disk or User Defaults [2].

NSJSONSerialization already supports decoding top-level fragments with the `JSONSerialization.ReadingOptions.allowFragments` setting, so I'm requesting introducing the same setting for encoding too: `JSONSerialization.WritingOptions.allowFragments`. Then JSONEncoder/JSONDecoder in Swift could use that to implement support for top-level fragments.


[1]: https://tools.ietf.org/html/rfc7159#section-3
[2]: https://github.com/sindresorhus/Defaults/blob/7ce06f346e18fe774284b29323c07c99e0a35f19/Sources/Defaults.swift#L83-L92

Steps to Reproduce:
 

Expected Results:
I expected this to work:

```swift
let intData = "99".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.allowFragments = true
try decoder.decode(Int.self, from: intData) // 99
```

Actual Results:
It doesn't work.

Version:
macOS 10.13

Notes:

Comments

Marked as duplicate

Engineering has determined that your bug report (43035278) is a duplicate of 38549586 and will be closed.

By sindresorhus at Aug. 14, 2018, 5:23 p.m. (reply...)

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!