Mar 21, 2024 iOS

How to read data from a CSV file and convert it to JSON in Swift

To read data from a CSV file and convert it to JSON in Swift, you can follow these steps:

  1. Read the CSV file line by line.
  2. Parse each line into an array of values.
  3. Convert the array into a dictionary, using the CSV header as keys.
  4. Serialize the dictionaries into JSON format.

Data can be saved in a tabular format using a CSV file, which is a comma-separated value file with the.csv extension. This article explains how to convert CSV data to JavaScript Object Notation (JSON) without the need of any external npm packages. The values of any row can be separated by commas, and as is well known, different columns can also be split by commas, which is the primary distinction from the standard conversion.

Using this method, we will import the CSV file’s contents into an array and divide it according to a delimiter. The CSV’s rows will all be transformed into JSON objects and placed to the resultant array, which will also undergo a JSON conversion before a matching JSON output file is produced.

Approach: To get at the solution, take the following actions:

Using the default fs npm package, read the CSV file.
Split the data into an array after converting it to a string.
Make an array of headers.
Do the following for each of the n-1 remaining rows:
To add the values from the current row to an empty object, create one.

To alter the delimiter and save the created string in a new string s, declare a string str as the current array value.
When we come across an initial quotation (“”), we leave the commas in place; otherwise, we substitute pipe “|” for them.
As we navigate over characters, keep adding them to a String s.
Using the pipe delimiter |, divide the text, then put the values in an array called properties.
If a value for a header has multiple pieces of data separated by commas, we save it as an array; otherwise, the value is stored straight.
Incorporate the produced item into our result array.

import UIKit

let csvFile =
"""
Name,Age,Address,Phone Number,Email,Favorite Number,Employed
Boone Malimoe,19,7259 Anhalt Court,776-410-0007,[email protected],142,false
Burgess Greasley,33,04 Ridge Oak Street,649-893-5297,[email protected],337,true
Derwin Brunel,13,0843 Bunting Hill,790-611-6437,[email protected],961,true
Sheffie Spadotto,55,5298 Grover Court,265-791-1163,[email protected],479,true
Courtney Fearnyhough,63,2102 Garrison Circle,502-971-1269,[email protected],876,true
Melloney Stickens,19,97934 Crownhardt Plaza,145-301-1842,[email protected],852,false
Ellery Geere,53,7 Kedzie Center,515-764-9730,[email protected],vis,false
Nikki Goodere,61,6 Canary Parkway,827-542-0107,[email protected],0,true
Annabela Riddel,34,9132 Westridge Way,605-920-8468,[email protected],672,false
"""

struct Person: Codable {
    var name: String
    var age: Int
    var address: String
    var phoneNumeber: String
    var email:String
    var favoriteNumber: Int
    var employed: Bool
}

var persons = [Person]()

do {
    let row  = csvFile.components(separatedBy:"\n")
    
    for (index,row) in row.enumerated() {
        if index == 0 { continue}
        let coloums  = row.components(separatedBy: ",")
        let name = coloums[0]
        let age = Int(coloums[1])
        let address = coloums[2]
        let phoneNumeber = coloums[3]
        let email = coloums[4]
        let favoriteNumber = Int(coloums[5])
        let employed = Bool(coloums[6])
        
        let eachperson = Person(name: name, age: age ?? 0, address: address,phoneNumeber: phoneNumeber,email: email, favoriteNumber: favoriteNumber ?? 0,employed: employed ?? false)
        persons.append(eachperson)
    }
    let jsonData = JSONEncoder()
    let dataJson = try jsonData.encode(persons)
    if let json = String(data: dataJson, encoding: .utf8) {
      print(json)
        
    }
   
} catch {
    print("error")
}