-2

Hi i am a newbie to Swift and i'm now trying to get data using JSON. i have completed getting a JSON data but have no idea how to get the value part using the key. The code below is the part i don't get and trying to solve in a different IDE.

var data = items?[0]["locplc_telno"]
print(data)


var items = Optional([["locplc_telno": Optional("054-602-7799"), ...]])

So the question is:

how can i get "054-602-7799" part using "locplc_telno? I have tried

items?[0]["locplc_telno"]

but got a "nil"

077tech
  • 5
  • 2
  • 2
    "i have completed getting a JSON data" If what you have is an array of dictionaries, I would say, no you haven't. You should be using Codable so that you can obtain your data as a nest of structs. – matt Jul 14 '22 at 13:50
  • That code in itself should work. – Joakim Danielson Jul 14 '22 at 13:54
  • Check this out https://stackoverflow.com/questions/30049265/dictionary-in-swift for how to use dictionaries, & this for codable: https://stackoverflow.com/questions/50086418/codable-swift-4 – Timmy Jul 14 '22 at 14:14

2 Answers2

0

Here are a couple of ways to print values of the dictionary.

var items = Optional([["locplc_telno": Optional("054-602-7799")]])

for item in items! {
    for (key, value) in item {
        print(key, value ?? "")
    }
}
    
print(items?.first?["locplc_telno"])
cora
  • 1,916
  • 1
  • 10
  • 18
0

You can use if let

let text = "[{\"locplc_telno\":\"054-602-7799\"}]"
if let data = text.data(using: .utf8) {
    do {
        let res =  try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]
        if let telno = res?[0]["locplc_telno"] {
            print(telno)
        }
    } catch {
        print(error.localizedDescription)
    }
}

You will get

> 054-602-7799
Nansen
  • 1
  • 1