1

I am getting data back from a web-server and I am trying to access the data within the JSON object. I am having some issues with accessing it.

The JSON looks like this:

{
     "faults": [
      {
        "FaultCodeType": "X",
        "ErrorType": "System",
        "Description": "Response failed for reason 1"
      },
      {
        "FaultCodeType": "Y",
        "ErrorType": "System",
        "Description": "Response failed for reason 2"
      }
     ],
     "responseInfo": {},
     "responseInfo2": {},
     "responseInfo3": {}
}

Should I use JSON.parse?

JSON.stringify?

I have the method:

loadData(dataPassed) {
  this.angularService.searchWithData(dataPassed).subscribe(
data => {
const fault = data[0];
const fault2 = data[1];
console.log('Data is here = ' + data); // returns the JSON
console.log('Request = ' + JSON.stringify(data)); // shows the JSON
console.log(fault);  // undefined
console.log(fault2); // undefined
  }
}

It is not working though, any help would be greatly appreciated.

4
  • please tell what is the error you are facing? Commented Apr 14, 2020 at 12:26
  • The data when I console.log() is coming back as undefined. If I console.log the whole response (data) all I get is object Object. Commented Apr 14, 2020 at 12:30
  • where are you trying to display data/or running console.log Commented Apr 14, 2020 at 12:34
  • I updated the original post Commented Apr 14, 2020 at 12:39

2 Answers 2

1

You are getting undefined because of

const fault = data[0];
const fault2 = data[1];

as your data is object not array therefore fault[0] does not exists

try

const fault = data.faults[0];
const fault2 = data.faults[1];
Sign up to request clarification or add additional context in comments.

Comments

1

To access faults:

const faults = data.faults;

Then you can iterate over those faults:

faults.forEach(f -> {
     console.log('f.FaultCodeType', f.FaultCodeType);
     console.log('f.ErrorType', f.ErrorType);
     console.log('f.Description', f.Description);
})

To access responseInfo, responseInfo2 or responseInfo3:

console.log('data.responseInfo', data.responseInfo);
console.log('data.responseInfo2', data.responseInfo2);
console.log('data.responseInfo3', data.responseInfo3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.