If you're representing this structure in Swift, use square brackets for the dictionaries, as well as for the arrays. And don't forget to unwrap optionals:
let z = [
[
"Name":[
"First":"Tika",
"Last":"Pahadi"
],
"City":"Berlin",
"Country":"Germany"
]
]
if let name = z[0]["Name"] as? [String: String], let firstName = name["First"] {
// use firstName here
}
But let's say you really received that JSON as a result of some network request with URLSession
. You could then parse that with JSONSerialization
:
do {
if let object = try JSONSerialization.jsonObject(with: data) as? [[String: Any]],
let name = object[0]["Name"] as? [String: String],
let firstName = name["First"] {
print(firstName)
}
} catch {
print(error)
}
Or better, in Swift 4, we'd use JSONDecoder
:
struct Name: Codable {
let first: String
let last: String
enum CodingKeys: String, CodingKey { // mapping between JSON key names and our properties is needed if they're not the same (in this case, the capitalization is different)
case first = "First"
case last = "Last"
}
}
struct Person: Codable {
let name: Name
let city: String
let country: String
enum CodingKeys: String, CodingKey { // ditto
case name = "Name"
case city = "City"
case country = "Country"
}
}
do {
let people = try JSONDecoder().decode([Person].self, from: data) // parse array of `Person` objects
print(people)
} catch {
print(error)
}