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.
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.
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 .
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.
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With