-1

I need to check a json response and find out if the response has a key.

I found other similar questions but they are working with libraries like SwiftyJSON.

I don't want to use that.

I need to know if its possible to do this without using any third party libs?

My current code is this:

    let data = str.data(using: .utf8)!
      do {
      if let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
          {
         print(jsonArray)
    
    // I NEED TO DO CHECKS HERE...
    // something like this:
    
    if (jsonArray['someKey'] = exist){
    
    do something here
    
    }else{
    
    do something else
    
    }
    
    
    }

}

Is this possible at all?

drago
  • 1,148
  • 2
  • 16
  • 35
  • Of course it is, it Is impossible to help you specifically without seeing what you are doing but [this SO question](https://stackoverflow.com/questions/67195920/decode-json-from-the-nested-container-and-check-its-type-dynamically-for-typecas/67202497#67202497) has an example in the answer where in the `ConfigObject` the `type` is checked. you can also switch `try coder.decode(String.self, forKey: .key)` to `try coder.decodeIfPresent(String.self, forKey: .key)`. It all depends on what you are trying to do SO is full of questions on the topic – lorem ipsum May 20 '21 at 19:09
  • @loremipsum, I'm not using ConfigObject in my code. I'm simply doing a POST to a remote url and getting a JSON response from that URL. Sometimes the json has an extra key and sometimes it doesn't. I need to check to see if the extra key exist in the response. – drago May 20 '21 at 19:18
  • `ConfigObject` is what the other OP was using I was just pointing you to where to look so you can find a sample. – lorem ipsum May 20 '21 at 19:19
  • You can still do what @loremipsum suggests with optionals in your `struct`, then check if the key exists with `if container.contains(.yourKey)...` – Will May 20 '21 at 19:20

1 Answers1

1

Try using:

if let value = jsonArray["someKey"] {
   // If key exist, this code will be executed
} else {
  // If key does not exist, this code will be executed
}
Shivani Bajaj
  • 996
  • 10
  • 23