问题
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
回答1:
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);
回答2:
You can use JSON.parse method to parse a json data in string format.It will return a json object.In your case.
var response = JSON.stringify('{"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"}
')
var error_message = response.responseText.error_description
error_message variable contains your error message
来源:https://stackoverflow.com/questions/55090672/how-to-read-the-value-from-json-stringify-in-my-case