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

爷,独闯天下 提交于 2020-01-04 05:55:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!