在我的案例中如何读取Json Stringify的值?

问题描述 投票:2回答:2

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

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链接

jquery json stringify
2个回答
3
投票

你必须解析responseText属性,因为它是一个JSON字符串。

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
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.