Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 710
Kocio Avatar asked May 11 '16 15:05

Kocio


People also ask

How do you check if a key is present in JSON or not?

Check if the key exists or not in JSON if it is present directly to access its value instead of iterating the entire JSON. Note: We used json. loads() method to convert JSON encoded data into a Python dictionary. After turning JSON data into a dictionary, we can check if a key exists or not.

How do you check if a key is present in a JSON in Javascript?

Example 2: Check if Key Exists in Object Using hasOwnProperty() The key exists. In the above program, the hasOwnProperty() method is used to check if a key exists in an object. The hasOwnProperty() method returns true if the specified key is in the object, otherwise it returns false .

How do you check if a JSON has a key in python?

Python Program to Check if a Key Exists in a JSON String To access the values you should convert the JSON string into a python dictionary by using 'json. loads()' method after importing the 'json' module. Then you can check whether a key exists in the dictionary or not and if it exists, you can access the value.


1 Answers

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")
    }
}
like image 97
Eric Aya Avatar answered Oct 13 '22 12:10

Eric Aya