site-icon The Average Learner

How To Parse A JSON With SwiftyJSON

Jan 28, 2024
Programming swiftuixcodeswift
2 Minutes
270 Words
How To Parse A JSON With SwiftyJSON

What is SwiftyJSON?

SwiftyJSON is a third party library for decoding JSON file more easily in your Xcode project.

Why do you need it?

It is considered the best practise to encode and decode JSON with predefined type. However, the downside of using the built-in JSONDecoder is that it is a hassle to deal with dynamic JSON. Even if you could manage to get it done, it would still need a lot of work just to get it right, which is not ideal.

Dynamic JSON example

Image you have a JSON looks like this:

1
{
2
"data": {
3
"variable_1": "some text"
4
}
5
}

Where the variable_1 key will be changed dynamically, you cannot just decode the data simply using data.title. What if it’s data.description next time?

In JavaScript, we can easily do this:

1
let dynamicKey = 'variable'
2
const json = JSON.parse(JSONObejct)
3
console.log(json.data[`${dynamicKey}_1`])

You can access the value just by putting a dynamic string in to [] behind data. However, you cannot do this in Swift.

That’s why SwiftyJSON comes into play.

To Parse a JSON using SwiftyJSON

With the help of SwiftyJSON, you can do this:

1
let json = JSON(data: JSONObejct)
2
let dynamicVar = "variable_1"
3
if let extracted = json[0]["data"]["\(dynamicVar)"].string { // It's wrapped with Optional automatically
4
//Now you got your value inside data.variable_1, just change your variable value for dynamicVar as needed.
5
print(extracted) // some text
6
}

It is pretty much the same way you do in JavaScript.

Direct and simple.

Bottom line

Even though the library still works, the library is not maintained anymore. The latest commit was 2 years ago.

I will still be using it for my projects though, because it saves me a lot of time and hassle.

Almost a must-have library for dealing with JSON.

Article title:How To Parse A JSON With SwiftyJSON
Article author:Hong C.
Release time:Jan 28, 2024
Copyright 2025
Sitemap
Privacy Policy
Terms of Service

Theme by Astro-Yi