在我的情况下,如何从Json Stringify读取值?

时间:2019-03-10 17:56:33

标签: jquery json stringify

我验证用户登录后,如果登录失败,则会显示以下错误消息

jquery

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

错误消息

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."}

我只想显示The user name or password is incorrect条消息

我已经检查了此jQuery - Get value from JSON Stringify链接

2 个答案:

答案 0 :(得分:3)

由于它是JSON字符串,因此您必须解析responseText属性。

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);

答案 1 :(得分:2)

您可以使用JSON.parse方法以字符串格式解析json数据,它将返回一个json对象。

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 变量包含您的错误消息