UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to parse JSON using SwiftyJSON

Swift version: 5.6

Paul Hudson    @twostraws   

SwiftyJSON is a super-simplified JSON parsing library that gives you clearer syntax than the built-in iOS libraries (yes, even more than JSONEncoder from Codable), and is free.

You can download it from here – unzip the file you downloaded, then look in its Source directory and drag SwiftyJSON.swift into your Xcode project. To use SwiftyJSON, you need to convert your JSON string into a Data object, then send it in for parsing. Once that's done, you simply request data in the format you want, and (here's the awesome bit) SwiftyJSON is guaranteed to return something.

That "something" is going to be your data, if all things are in good shape. But if you requested the wrong thing (either with a typo, or because you didn't understand your JSON structure correctly) or if the JSON has changed, SwiftyJSON will just return a default value instead.

To get you started, here is some example JSON:

let json = "{ \"people\": [{ \"firstName\": \"Paul\", \"lastName\": \"Hudson\", \"isAlive\": true }, { \"firstName\": \"Angela\", \"lastName\": \"Merkel\", \"isAlive\": true }, { \"firstName\": \"George\", \"lastName\": \"Washington\", \"isAlive\": false } ] }"

That contains an array of three people, each of which have a first name, a last name, and an "is alive" status. To parse that using SwiftyJSON and print out all the first names, here's the code:

if let data = json.data(using: .utf8) {
    if let json = try? JSON(data: data) {
        for item in json["people"].arrayValue {
            print(item["firstName"].stringValue)
        }
    }
}

It's the arrayValue and stringValue properties that do all the magic: the first one returns the array of people or an empty array if the "people" element didn't exist, and the second one returns the "firstName" property of a person, or an empty string if it wasn't set. So, no matter what happens, that code will work, which means it's easy to write and safe to run.

Sometimes JSON has quite deeply nested dictionaries, but that's OK: SwiftyJSON can navigate through multiple levels in one call, and if any one level fails you'll still get back your default value. For example, if you have JSON like this:

{  
   "metadata":{  
      "responseInfo":{  
         "status":200,
         "developerMessage":"OK",
      }
   }
}

You might want to check that the status code is 200 before continuing. To do that, just read the "metaData", "responseInfo" and "status" values all at once, and ask SwiftyJSON for its intValue – you'll either get the correct number (200) or 0 if any of those values don't exist. Like this:

if json["metadata"]["responseInfo"]["status"].intValue == 200 {
    // we're OK to parse!
}
Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 7.0 – see Hacking with Swift tutorial 7

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.