JSON parsing in Swift

Mr.Javed Multani
2 min readOct 2, 2020

Here is the JSON File we will be using called animals.json

{
"Sea Animals": [
{"name": "Fish",
"question": "How many species of fish are there?" },{
"name": "Sharks",
"question": "How long do sharks live?"
},
{
"name": "Squid",
"question": "Do squids have brains?"
},
{
"name": "Octopus",
"question": "How big do octopus get?"
},
{
"name": "Star Fish",
"question": "How long do star fish live?"
}],"mammals": [
{"name": "Dog",
"question": "How long do dogs live?"
},{
"name": "Elephant",
"question": "How much do baby elephants weigh?"}, {"name": "Cats",
"question": "Do cats really have 9 lives?"
},{
"name": "Tigers",
"question": "Where do tigers live?"}, {"name": "Pandas",
"question": "WHat do pandas eat?" }]}

Import your JSON File in your project
You can perform this simple function to print out your JSON file

func jsonParsingMethod() {
//get the filelet filePath = Bundle.main.path(forResource: "animals", ofType: "json")

let content = try! String(contentsOfFile: filePath!)let data: Data = content.data(using: String.Encoding.utf8)!let json: NSDictionary = try! JSONSerialization.jsonObject(with: data as Data,
options:.mutableContainers) as! NSDictionary//Call which part of the file you'd like to pareif let results = json["mammals"] as? [[String: AnyObject]] {for res in results {
//this will print out the names of the mammals from out file.
if let rates = res["name"] as? String { print(rates)} }}
}

If you want to put it in a table view, I would create a dictionary first with an NSObject. Create a new swift file called ParsingObject and create your string variables.

Make sure that the variable name is the same as the JSON File

For example, in our project we have name and question so in our new swift file, we will use

var name: String?
var question: String?

Initialize the NSObject we made back into our ViewController.swift var array = ParsingObject Then we would perform the same method we had before with a minor modification.

func jsonParsingMethod() {
//get the filelet filePath = Bundle.main.path(forResource: "animals", ofType…
Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer