Reputation: 3527
I'm trying to retrieve the error message
from my JSON object using jQuery. How would I go about doing this? Thanks!
My JSON looks like this:
{
"error":{
"errors":[
{
"domain":"global",
"reason":"invalidParameter",
"message":"Invalid value 'asdfcom.com'. Values must match the following regular expression: 'http(s)?://.*'",
"locationType":"parameter",
"location":"url"
}
],
"code":400,
"message":"Invalid value 'asdfcom.com'. Values must match the following regular expression: 'http(s)?://.*'"
}
}
And my Javascript looks like this:
error: function(xhr, status, error) {
$("#mobileResults").css("color", "red");
$("#mobileResults").text(xhr.responseText);
console.log(xhr.responseText)
$('.fa-spinner').hide();
}
Upvotes: 0
Views: 111
Reputation: 4147
It's simple:
var jsonObj = JSON.parse(xhr.responseText); //your object;
var message = jsonObj.error.errors[0].message; // Values must match the following regular expression:
var outsideMes = jsonObj.error.message; // Values must match the following regular expression:
You can try with this snippet, it works properly
var obj = {
"error": {
"errors": [{
"domain": "global",
"reason": "invalidParameter",
"message": "Invalid value 'asdfcom.com'. Values must match the following regular expression: 'http(s)?://.*'",
"locationType": "parameter",
"location": "url"
}],
"code": 400,
"message": "Invalid value 'asdfcom.com'. Values must match the following regular expression: 'http(s)?://.*'"
}
}
console.log(obj.error.errors[0].message);
console.log(obj.error.message);
Upvotes: 3
Reputation: 51
Try to use jQuery.parseJSON
method.
var jsonObj = jQuery.parseJSON(xhr.responseText);
console.log(jsonObj.message);
Upvotes: 0