How to use typealias to make JSON parsing more readable in Swift

Update: If you’re using Swift 2, check out How to parse JSON with Swift 2 to see how to handle JSON in Swift 2.

The typical approach I’ve seen to JSON parsing in Swift with [String: AnyObject] dictionaries is fine, but not all that readable. Let’s see if we can fix that, making it a little easier to understand and maintain.

We’ll use the following JSON (copied and tweaked from David Owens II):

{
    "blogs": [
        {
            "needspassword": true,
            "id": 73,
            "url": "http://remote.bloxus.com/",
            "name": "Bloxus test"
        },
        {
            "needspassword": false,
            "id": 74,
            "url": "http://flickrtest1.userland.com/",
            "name": "Manila Test"
        }
    ],
    "stat": "ok"
}

Here’s the typical approach I’ve seen (and used myself) when parsing JSON:

if let json = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: nil) as? [String: AnyObject] {
    if let blogs = json["blogs"] as? [[String: AnyObject]] {
        // parse blogs
    }
}

And this is fine, but we can do better. It’s not easy to read and understand quickly. Too many brackets and too many [String: AnyObject] references. It’s easy to get lost in the square brackets (and this isn’t even Objective-C!). To get rid of some of those, we can use a typealias:

typealias JSONDictionary = [String: AnyObject]

So instead of referring to [String: AnyObject] as we parse our JSON, we’re just going to call it a JSONDictionary. Like so:

if let json = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: nil) as? JSONDictionary {
    if let blogs = json["blogs"] as? [JSONDictionary] {
        // parse blogs
    }
}

Now it’s clear that we expect a JSONDictionary from our data, and we expect blogs to be an array of JSONDictionary objects. Simpler, more readable, and dare I say more idiomatic.

If you want to take it a step further, you could do this with JSON arrays, too – you can define a typealias for [JSONDictionary] – the array of JSONDictionary objects – if you want. To me, it’s clear enough as it is. I can easily see that it’s an array of dictionaries, so taking the next step isn’t necessary.

Use typealias to write more readable JSON code in Swift by simplifying dictionary types. And you don’t have to stop there – you can use typealias for functions, tuples, too. I’ll leave it up to you to decide what else you can simplify with it.