How to Extract Data from JSON Using a Dictionary in Swift
In the previous article "Reading and Writing JSON in Swift", we introduced how to define a struct and convert a JSON string into a struct object.
Here, we will explain how to extract data from JSON in Swift using a Dictionary, without defining a struct.
Convert a JSON String to a Swift Dictionary
This time, we will convert a JSON string into a Swift Dictionary and retrieve data from it.
As an example, we will extract values from the following JSON string.
This is the JSON returned as a response from the CDTFA Tax Rate API, which retrieves tax rates in California.
{
"taxRateInfo":[
{
"rate":0.0775,
"jurisdiction":"ANAHEIM",
"city":"ANAHEIM",
"county":"ORANGE",
"tac":"300110370000"
}
],
"geocodeInfo":{
"bufferDistance":50
},
"termsOfUse":"https://www.cdtfa.ca.gov/dataportal/policy.htm",
"disclaimer":"https://www.cdtfa.ca.gov/dataportal/disclaimer.htm"
}
To extract the values of rate and city from taxRateInfo in this JSON string, you can do the following:
import Foundation
let jsonString = """
{
"taxRateInfo":[
{
"rate":0.0775,
"jurisdiction":"ANAHEIM",
"city":"ANAHEIM",
"county":"ORANGE",
"tac":"300110370000"
}
],
"geocodeInfo":{
"bufferDistance":50
},
"termsOfUse":"https://www.cdtfa.ca.gov/dataportal/policy.htm",
"disclaimer":"https://www.cdtfa.ca.gov/dataportal/disclaimer.htm"
}
"""
do {
let jsonDict = try JSONSerialization.jsonObject(with: Data(jsonString.utf8)) as? [String: Any]
let taxRateInfos = jsonDict?["taxRateInfo"] as? [[String: Any]]
if taxRateInfos != nil && taxRateInfos!.count > 0 {
let rate = taxRateInfos![0]["rate"]
let city = taxRateInfos![0]["city"]
print("City: \(city ?? ""), Tax Rate: \(rate ?? "")")
}
} catch {
print("Unexpected error: \(error).")
}
On line 23, we use the JSONSerialization.jsonObject() method to convert jsonString into a jsonObject, and then further cast it into a [String: Any] Dictionary and assign it to jsonDict.
On line 24, we take the value for the key taxRateInfo from jsonDict, cast it into an array of [String: Any] Dictionaries, and assign it to taxRateInfos.
If taxRateInfos is not nil and contains at least one element, we retrieve the values of rate and city from the first element (index = 0) and print them.
When run in a playground, the result is as follows, showing that the values for city and rate have been successfully retrieved.
As shown, you can extract values from a JSON string by sequentially converting its structure into Dictionaries, step by step, until reaching the desired values.
This is useful when you don't need to define a struct and convert the entire JSON into an object, but instead only want to extract and use specific parts of the data.
That wraps up how to extract data from JSON in Swift using a Dictionary.