How to check if key exists in swiftyJSON when json contain array with no keys
Asked Answered
R

1

15

I know about swiftyJSON method exists() but it does not seem to work always as they say. How can I get proper result in this case below? I cannot change JSON structure because I am getting this through client's API.

var json: JSON =  ["response": ["value1","value2"]]
if json["response"]["someKey"].exists(){
    print("response someKey exists")
}

Output:

response someKey exists

That shouldn't be printed because someKey does not exist. But sometimes that key comes from client's API, and i need to find out if it exists or not properly.

Ramonitaramos answered 11/5, 2016 at 15:50 Comment(0)
S
35

It doesn't work in your case because the content of json["response"] is not a dictionary, it's an array. SwiftyJSON can't check for a valid dictionary key in an array.

With a dictionary, it works, the condition is not executed, as expected:

var json: JSON =  ["response": ["key1":"value1", "key2":"value2"]]
if json["response"]["someKey"].exists() {
    print("response someKey exists")
}

The solution to your issue is to check if the content is indeed a dictionary before using .exists():

if let _ = json["response"].dictionary {
    if json["response"]["someKey"].exists() {
        print("response someKey exists")
    }
}
Stubby answered 11/5, 2016 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.