Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created September 18, 2021 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/c301960834d5500be4512da13e12c6eb to your computer and use it in GitHub Desktop.
Save IanKeen/c301960834d5500be4512da13e12c6eb to your computer and use it in GitHub Desktop.
Decode an object nested under a key
let json = """
{
"results": [
{"value": "foo"},
{"value": "bar"},
{"value": "baz"}
]
}
"""
struct Item: Decodable {
let value: String
}
let items = try JSONDecoder().decode([Item].self, from: Data(json.utf8), under: "results")
print(items) // [Item(value: "foo"), Item(value: "bar"), Item(value: "baz")]
extension TopLevelDecoder {
func decode<T: Decodable>(_ type: T.Type, from input: Input, under: String) throws -> T {
let decoder = try decode(_Decoder.self, from: input).decoder
let container = try decoder.container(keyedBy: AnyCodingKey.self)
return try container.decode(T.self, forKey: .init(under))
}
}
private struct _Decoder: Decodable {
var decoder: Decoder
init(from decoder: Decoder) throws {
self.decoder = decoder
}
}
@IanKeen
Copy link
Author

IanKeen commented May 16, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment