How to check the Json object is exists or not using Jquery?

Viewed 36

I am returning error message using ajax. the return object like below

{"readyState":4,"responseText":"{\"Message\":\"The request is invalid.\",\"ModelState\":{\"\":[\"Email 'dsfasdf' is invalid.\"]}}","responseJSON":{"Message":"The request is invalid.","ModelState":{"":["Email 'dsfasdf' is invalid."]}},"status":400,"statusText":"Bad Request"}

I want to know whether (showError.responseText).ModelState[""] is exist or not

I tried both following code. But doesn't work

if ((showError.responseText).ModelState[""]) {
            console.log('Key is exist in Object!');
}
if ((showError).hasOwnProperty("ModelState[0]")) {
    console.log('Key is exist in Object!');
}
1 Answers

The value you're returning contains nested JSON. jQuery will deserialise the parent object for you (assuming the MIME types of the response are configured correctly) however you will need to manually deserialise repsonseText before you can work with it. Try this:

var response = {
  "readyState": 4,
  "responseText": "{\"Message\":\"The request is invalid.\",\"ModelState\":{\"\":[\"Email 'dsfasdf' is invalid.\"]}}",
  "responseJSON": {
    "Message": "The request is invalid.",
    "ModelState": {
      "": ["Email 'dsfasdf' is invalid."]
    }
  },
  "status": 400,
  "statusText": "Bad Request"
}

// in your AJAX handler function:
var rt = JSON.parse(response.responseText);
if (rt.ModelState)
  console.log(rt.ModelState);

Related