Swift decode json with key starting as a number

Viewed 626

I have a json in following format:

let json = """
{
    "stuff": {
        "1": "one",
        "2": "two",
        "4": "four"
    }
}

question is how can i make my

struct Stuff: Codable, Equatable {
    let 1: String
    let 2: String
    let 4: String
}

compile and work?

i use to call this with below, and it works fine for everything but if let name starts with number it obviously won't compile

let obj = try? JSONDecoder().decode(T.self, from: data)
2 Answers

You can't. A variable must not start with a numeric character. Unalterable rule.

But you can map the names with CodingKeys

struct Stuff: Codable, Equatable {
    let one, two, four: String

    private enum CodingKeys : String, CodingKey { case one = "1",  two = "2", four = "4"}
}

You can't. RFC 7159 standard for JSON dictates that the object key must be a string.

object = begin-object [ member *( value-separator member ) ]
           end-object

member = string name-separator value
Related