当 json 包含没有键的数组时,如何检查 swiftyJSON 中是否存在键
How to check if key exists in swiftyJSON when json contain array with no keys
我知道 swiftyJSON 方法 exists() 但它似乎并不像他们所说的那样总是有效。
在下面的这种情况下,我怎样才能得到正确的结果?我无法更改 JSON 结构,因为我是通过客户的 API.
获得的
var json: JSON = ["response": ["value1","value2"]]
if json["response"]["someKey"].exists(){
print("response someKey exists")
}
输出:
response someKey exists
不应打印,因为 someKey 不存在。但有时该密钥来自客户的API,我需要查明它是否存在。
它不适用于您的情况,因为 json["response"]
的内容不是字典,而是数组。 SwiftyJSON 无法检查数组中的有效字典键。
使用字典,有效,条件未执行,如预期:
var json: JSON = ["response": ["key1":"value1", "key2":"value2"]]
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
您的问题的解决方案是在使用 .exists()
:
之前检查内容是否确实是字典
if let _ = json["response"].dictionary {
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
}
我知道 swiftyJSON 方法 exists() 但它似乎并不像他们所说的那样总是有效。 在下面的这种情况下,我怎样才能得到正确的结果?我无法更改 JSON 结构,因为我是通过客户的 API.
获得的var json: JSON = ["response": ["value1","value2"]]
if json["response"]["someKey"].exists(){
print("response someKey exists")
}
输出:
response someKey exists
不应打印,因为 someKey 不存在。但有时该密钥来自客户的API,我需要查明它是否存在。
它不适用于您的情况,因为 json["response"]
的内容不是字典,而是数组。 SwiftyJSON 无法检查数组中的有效字典键。
使用字典,有效,条件未执行,如预期:
var json: JSON = ["response": ["key1":"value1", "key2":"value2"]]
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
您的问题的解决方案是在使用 .exists()
:
if let _ = json["response"].dictionary {
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
}