Search code examples
jqueryjsonstringify

How to read the value from Json Stringify in my case?


After I validate user login, if it failed it will show the following error message

jquery

console.log('Full error  = ' + JSON.stringify(showError));
console.log('test 1 =' + showError.responseText);

Error message

Full error  = {"readyState":4,"responseText":"{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}","responseJSON":{"error":"invalid_grant","error_description":"The user name or password is incorrect."},"status":400,"statusText":"Bad Request"}


test 1 ={"error":"invalid_grant","error_description":"The user name or password is incorrect."}

I want to display only The user name or password is incorrect message only

I already check this jQuery - Get value from JSON Stringify link


Solution

  • You have to parse the responseText property since it's a JSON string.

    console.log(JSON.parse(showError.responseText).error_description);
    
    // or using bracket notation
    console.log(JSON.parse(showError.responseText)['error_description']);
    

    var showError = {"readyState":4,"responseText":"{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}","responseJSON":{"error":"invalid_grant","error_description":"The user name or password is incorrect."},"status":400,"statusText":"Bad Request"} ;
    
    console.log(JSON.parse(showError.responseText).error_description);