How to check if a key exists in swiftyJSON when json contains an array without keys

I know that the swiftyJSON method exists (), but it does not always work, as they say. How can I get the correct result in this case below? I cannot change the JSON structure because I get it through the client API.

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

Output:

 response someKey exists

This should not be printed because someKey does not exist. But sometimes this key comes from the client API, and I need to find out if it exists or not.

+8
json ios swift swifty-json
source share
1 answer

In your case, this does not work, because the contents of json["response"] not a dictionary, it is an array. SwiftyJSON cannot validate a valid dictionary key in an array.

It works with the dictionary, the condition is not met, as expected:

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

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

 if let _ = json["response"].dictionary { if json["response"]["someKey"].exists() { print("response someKey exists") } } 
+13
source share

All Articles