Reputation: 735
I am trying to pull an error message from an external errors.txt file.
The contents of errors.txt is:
var data = {
'errors': [{
"code": "9999",
"message": {
row: 1,
col: 0,
data: 'ABC',
code: 20016,
message: 'Invalid code.'
}
},
{
"code": "9999",
"message": {
row: 1,
col: 0,
data: 'DEF!',
code: 20016,
volume: '100',
message: 'Invalid code.'
}
}],
"data": {
"report": null
},
"successMsg": null,
"errorMsg": null
}
I am trying to display the message (ie - "invalid code') and have tried the following, but no luck:
jQuery.getJSON('/js/errors.txt', function (data) {
// data is an array of objects
$.each(data, function () {
alert(this.errors[0].message[0].message);
});
});
What am I doing wrong?
Upvotes: 0
Views: 148
Reputation: 3083
Please try as below:
errors.txt
{
"errors": [
{
"code": "9999",
"message": {
"row": 1,
"col": 0,
"data": "ABC",
"code": 20016,
"message": "Invalid code."
}
},
{
"code": "9999",
"message": {
"row": 1,
"col": 0,
"data": "DEF!",
"code": 20016,
"volume": 100,
"message": "Invalid code."
}
}
],
"data": {
"report": null
},
"successMsg": null,
"errorMsg": null
}
script
<script>
$(function () {
$.getJSON('errors.txt', function (data) {
$.each(data, function () {
alert(data.errors[0].message.message);
});
});
});
</script>
Upvotes: 2
Reputation: 3892
When you are traversing your JSON with each loop try to use key & value(give your own name according to your coding choice) as parameter to it.
Please replace your inner $.each({ loop with below code
$.each(data, function (key, value) {
alert("Error Message : ", value[0].message.message);
});
Hope this helps to tackle the problem..
Upvotes: 1