Parsing a JSON Array in Swift

JavaScript Object Notation, or JSON, is a text-based data format that is used to store and transfer data across web and local networks. JSON is the most popular data format used in database connections because of its high data capacity and lightweight file size. In this tutorial, we will learn how to parse data from a JSON file in swift and use it in our console.

Sample JSON Data

The basic format of any JSON file consists of Javascript objects, that exist in a key:value pair often encapsulated in an array or dictionary. We will be using a simple JSON file so understand functions that extract data from JSON Files. For the steps in this tutorial, we will be using the following “companyData.json” file:

{
  "companyName": "Apple",
  "companyCEO": "Tim Cook",
  "yearFounded": 1976,
  "isPublic": true,
  "products": [
    "iPhone",
    "iPad",
    "iMac",
    "Airpods"
  ]
}

Now let’s see how we can decode this data and use it in our program.

Converting Data from JSON bytes to Swift objects

In Swift, data can either be encodable or decodable when working with JSON. Encodable means a type that can encode itself to an external format (Swift object to JSON bytes) whereas Decodable is when a type can decode itself from another format (JSON bytes to Swift Object). Generally, the term Codable is used which allows the data to be both encoded or decoded by Xcode. Our first step is to decode the data from the “companyData.json” file so that it can be used as Swift objects:

//Create a local path 
guard let jsonURl = Bundle(for: type(of: self)).path(forResource: "companyData", ofType: "json") else {
    return
}

//Convert PathURL to string 
guard let jsonString = try? String(contentsOf: URL(fileURLWithPath: jsonURL), encoding: String.encoding.utf8) else { 
   return
}

We need these 2 fundamental functions in order to convert the JSON data into objects that Swift can interpret. Our first method identifies the “company.json” file uploaded to Xcode, and the second method transforms this path into a String rather than a URL so it can be called later on.

Creating a struct to store JSON data in Swift

The next step is to store all the data from our JSON file into a native Swift Object, and the most common way to do so is by using a Swift struct, which automatically categorizes the JSON data based on the key:value pairs that we set. Like mentioned above, we need to set our struct as Codable, which allows the transfer of data both ways. Within our struct, we will need to specify all the different keys and the corresponding value type, verifying that they match those of the JSON file otherwise the parsing will fail. In our example:

struct Company: Codable {

   let companyName: String
   let companyCEO: String
   let yearFounded: Int
   let isPublic: Bool
   let products: [String]
}

Using this struct, we have successfully created a collection, to store all the data from our JSON File into the Swift Structure: Company

Creating a JSON Decoder in Swift

Once we have created our functions that establish a connection between the JSON and Swift, as well as a struct that can store the data from the JSON, we now need to actually create a Decoder that can pass the JSON Data into the struct. This can be done using:

 var company: Company?
        do {
            company = try JSONDecoder().decode(Company.self, from: Data(jsonString.utf8))
        } catch {
            print(Error.localizedDescrption)
        }

guard let info = company else {
            print("No data found while decoding")
            return
        }

Here we have first created the instance company for our struct Company?, and the set is as optional since we do not know whether all the data listed in the struct is present in the JSON File. To avoid the program from crashing if data is indeed missing, we have wrapped the code in a do-try-catch block, so that we can simply print the error. We have used the JSONDecoder(), which is a Swift object that allows us to decode data from external representations., like our JSON file. Using the decoder, we target the destination to be the struct Company?, which in this case itself, and we get the data from the jsonString that we created previously, which now turned the Data from type JSON to Strings.

We also need to greed the info instance, which is nothing but a localized variable that allows us to access the contents of the Company struct. We also need to bind this variable with an if-else statement, so if the company does turn out to be nil we can avoid the program from crashing. We can now use this variable info to display the parse information.

Checking the functionality of JSON Decoder

Now that we successfully created a decoder, we can now print the named values as:

//printing the values

print(info.companyName)
print(info.companyCEO)
print(info.yearFounded)
print(info.isPublic)
print(info.products)
//Output:

Apple
Tim Cook
1976
true
["iPhone", "iPad", "iMac", "Airpods"]

As you can see, we were successfully able to extract all the data from the JSON file. This is why JSON is so popular with database connections, which are nothing but thousands of JSON files being parsed from a web server to local devices, carrying high volumes of important data. JSON in Swift is extremely effective at complex programs like real-time API calling, Firebase and Cloud connections and so much more.

Leave a Reply

Your email address will not be published.