简体   繁体   English

当json包含没有键的数组时,如何检查swiftyJSON中是否存在键

[英]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. 我知道swiftyJSON方法exists()但它似乎并不总是如他们所说。 How can I get proper result in this case below? 在下面这种情况下如何获得正确的结果? I cannot change JSON structure because I am getting this through client's API. 我无法更改JSON结构,因为我通过客户端的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. 不应该打印,因为someKey不存在。 But sometimes that key comes from client's API, and i need to find out if it exists or not properly. 但有时候这个密钥来自客户端的API,我需要找出它是否存在。

It doesn't work in your case because the content of json["response"] is not a dictionary, it's an array. 它在你的情况下不起作用,因为json["response"]内容不是字典,它是一个数组。 SwiftyJSON can't check for a valid dictionary key in an array. SwiftyJSON无法检查数组中的有效字典键。

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() : 您的问题的解决方案是在使用.exists()之前检查内容是否确实是字典:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM