当json包含没有键的数组时,如何检查swiftyJSON中是否存在键 [英] How to check if key exists in swiftyJSON when json contain array with no keys
问题描述
我知道swiftyJSON方法exists()但它似乎并不像他们所说的那样工作。
如何在下面这种情况下获得正确的结果?我无法更改JSON结构,因为我通过客户端API获取此信息。
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")
}
输出:
response someKey exists
由于someKey不存在,因此不应打印。但有时候这个密钥来自客户端的API,我需要找出它是否存在。
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.
推荐答案
它没有'因为 json [response]
的内容不是字典而是你的情况,它是一个数组。 SwiftyJSON无法检查数组中的有效字典键。
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")
}
您的问题的解决方案是在使用 .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")
}
}
这篇关于当json包含没有键的数组时,如何检查swiftyJSON中是否存在键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!