SwiftyJSON: How To Parse JSON with Swift

SwiftyJSON is a Swift library for reading and processing JSON data. Learn how easy it is to use it and how it’s different from Codable and JSONSerialization
Written by

Chris C

Updated on

Apr 29 2024

Table of contents
    swiftyjson

    If you have been diving deep into iOS development you may have already come across accessing data/databases using URLSession, more so when you are trying to process data most especially JSON files, this is where SwiftyJSON comes in, So what is SwiftyJSON?

    What is SwiftyJSON?

    SwiftyJSON is a library that helps to read and process JSON data from an API/Server. So why use SwiftyJSON?

    Swift by nature is strict about data types and wants the user to explicitly declare it. This  becomes a problem as JSON data is usually implicit about data types.

    Lets say you want to get a list of student names in your JSON data. A typical Swift conversion of JSON data typically looks like this:

    if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
        let students = statusesArray[0]["students"] as? [String: Any],
        let studentName = user["name"] as? String {
        //we got the student name
    }
    

    Looks even more confusing and is prone to mistakes, yikes!.

    However, with the use of SwiftyJSON the codes above will only look like this:

    // json from networking or String
    let json = JSON(data: dataFromNetworkingOrString)
    if let studentName = json[0]["students"]["name"].string {
      //we got the student name
    }
    //SwiftJSON also automatically detects if the data you are using is from networking or from a json string

    See how easy that was? Easy to read and easy to write 🙂

    Part 1: Installation

    You need to have cocoapods installed for this, once that is ready, let’s create our xcode project. For this example we have created an xcode project called SwiftyJSONTest.

    We're going to need the SwiftyJSON pod in order to use SwiftyJSON
    We’re going to need the SwiftyJSON pod in order to use SwiftyJSON

    Now navigate to your project folder and open a terminal window, also navigate the terminal window to the project location.

    Navigate to your project folder via Terminal and type pod Init
    Navigate to your project folder via Terminal and type pod Init

    Once there you should do a “pod init” in your terminal

    It will then output a file named Podfile.

    Open the podfile and add the SwiftyJSON pod
    Open the podfile and add the SwiftyJSON pod

    Open the Podfile in Textedit and add the line pod “SwiftyJSON”, “[version number]” or just simply pod “SwiftyJSON”

    Save the file and in your terminal do a pod install, once it has finished installation it should have created a Pods folder, [projectname].xcworkspace, and a Podfile.lock.

    Run pod install and open the xcworkspace file.
    Run pod install and open the xcworkspace file.

    Open the file named [projectname.xcworkspace] and your project should have SwiftyJSON installed and ready to go

    Open the xcworkspace project file
    Open the xcworkspace project file

    Part 2: Using SwiftyJSON

    The Basics

    For this example we will be using httpbin.org’s JSON functionality to simulate our JSON response. We will also be using the pod Alamofire 5 to make out http calls easier.

    Our sample json response from httpbin looks like this:

    Here's some sample JSON
    Here’s some sample JSON

    For starters let’s start with a basic SwiftyJSON call getting the title of the slideshow:

    Here's SwiftyJSON in action
    Here’s SwiftyJSON in action

    The debug print looks like this:

    Printed output
    Printed output

    Getters

    SwiftyJSON has an option of getting optional and non-optional data and is quite straightforward. It also supports getting Array or Dictionary values.

    Optional

    For getting optional data you just need to simply set the type, for example:

    let studentname = json[“students”][“name”].string //for string
    	let hasAttended = json[“students”][“hasAttended”].bool //for boolean
    	let id = json[“students”][“id”].int //for integer
    

    Non-Optional

    For getting non-optional data you just need to simple set the type + value, to better illustrate:

    let studentname = json[“students”][“name”].stringValue //for string
    	let hasAttended = json[“students”][“hasAttended”].boolValue //for boolean
    	let id = json[“students”][“id”].intValue //for integer
    

    Array/Dictionary

    Getting Array or Dictionary values is also easy:

    let list: Array<JSON> = json["list"].arrayValue // If not an Array or nil, return []
    let user: Dictionary<String, JSON> = json["user"].dictionaryValue // If not a Dictionary or nil, return [:]
    

    Exists

    Typically, you might want to check a particular data exists in your json response, to do so just simply:

    json[“students”][“name”].exists() //returns a boolean
    

    Error Handling

    Typically your app will crash If the JSON is:

    • an array, the app may crash with “index out-of-bounds.”
    • a dictionary, it will be assigned to nil without a reason.
    • not an array or a dictionary, the app may crash with an “unrecognised selector” exception.

    However, this is automatically handled by SwiftyJSON making it not only convenient, but also practical to use, check out these examples to illustrate:

    // Out of bounds
    let json = JSON(["name", "age"])
    if let name = json[1000].string {
        // your code
    } else {
        print(json[999].error!) // "Array[1000] is out of bounds"
    }
    
    //Dictionary key does not exist
    let json = JSON(["name":"Francis", "age": 28])
    if let address  = json["address"].string {
        // your code
    } else {
        print(json["address"].error!) // "Dictionary["address"] does not exist"
    }
    
    //JSON reading error (incorrect format)
    let json = JSON(4321)
    if let name = json[0].string {
        // your code
    } else {
        print(json[0])       // "Array[0] failure, It is not an array"
        print(json[0].error!) // "Array[0] failure, It is not an array"
    }
    
    //JSON is not a dictionary
    if let name = json["name"].string {
        // your code
    } else {
        print(json["name"])       // "Dictionary[\"name"] failure, It is not an dictionary"
        print(json["name"].error!) // "Dictionary[\"name"] failure, It is not an dictionary"
    }
    
    

    Data Handling with Iteration

    We have covered the basics and features of SwiftyJSON but have yet to use it normally. Luckily, our sample data set has an attribute called “slides” that we can call and practice real world calls/iteration with.

    Working with Arrays

    We can break down and map our JSON data by putting it in arrays. To do so just simply get the .arrayValue of JSON and then map the data like so:

    Working with arrays using SwiftyJSON
    Working with arrays using SwiftyJSON

    These lines of code will result into this:

    printed output
    printed output

    See how easy it was to map? You now workable arrays of your JSON data to work with.

    Working with Dictionaries

    Handling data in as a Dictionary is relatively easy, you can use the built-in for function to iterate over keys and data/values from your JSON result like so:

    Working with dictionaries using SwiftyJSON
    Working with dictionaries using SwiftyJSON

    These lines of code will result into this:

    printed output
    printed output

    Super simple and does the trick! It even automatically handled the first element having no “items” and just simple set it as null, how cool was that!

    Merging separate JSON data

    If for some reason you would want to merge different JSON data from different sources then SwiftyJSON still has you covered! It is done by simply using the built-in .merge function:

    let original: JSON = [
        "firstname": "Francis",
        "age": 20,
        "skills": ["Coding", "Writing"],
        "address": [
            "city": "DVO",
            "zip": "8000",
        ]
    ]
    
    let update: JSON = [
        "lastname": "Doe",
        "age": 28,
        "skills": ["Cooking"],
        "address": [
            "street": "Kilowatt St",
            "city": "Davao City"
        ]
    ]
    
    let updated = original.merge(with: update)
    // updated value is now
    // [
    //     "firstname": "Francis",
    //     "lastname": "Fuerte",
    //     "age": 28,
    //     "skills": ["Coding", "Writing", "Cooking"],
    //     "address": [
    //         "street": "Kilowatt St",
    //         "zip": "8000",
    //         "city": "Davao City"
    //     ]
    // ]
    

    Notice that any new data is added to an existing array, while any new data with the same key like “age” and “city” are updated with the new value!. This is very helpful with comparing and updating old data and new data.

    Conclusion

    That’s about it for this first look into to SwiftyJSON, with these information you should be equipped enough to utilize it in your swift project, if you ever need extra info you can check out the official guide and documentation here. Good luck and have fun coding! 🙂


    Further Reading




    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris