Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display the contents of an array { data: { results: [ [Object] ], total: 1, page: 1 }, error: null } in the response?

I have the following piece of code:


let result = null;
    await fetch(request)
      .then((response) => {
        if (response.status === 201) {
          console.log("Success");
          result = response.json();
        } else {
          throw new Error("Something went wrong on API server!");
        }
      })
      .catch((error) => {
        console.error(error);
      });
    console.log("Response:", await result);
  });
});

and in response I received:

[0-0] Success
[0-0] Response: { data: { results: [ [Object] ], total: 1, page: 1 }, error: null }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But in Postman the response looks like this:

{
    "data": {
        "results": [
            {
                "customerId": 123,
                "firstName": "Name",
                "lastName": "LastName",
                "displayName": "Name LastName",
                "phoneNumber": "4159436367",
                "email": "email@email.com",
                "notes": null,
                "memberNumber": null,
                "highlights": null
            }
        ],
        "total": 1,
        "page": 1
    },
    "error": null
}

How to display the contents of an array in response, for viewing like in Postman?
Thanks

I tried to add this code:

const parsedResponce = result;
const obj = JSON.parse(parsedResponce);
console.log(obj.phoneNumber);

After last

console.log("Response:", await result);

And received

SyntaxError: Unexpected token o in JSON at position 1

>Solution :

You can use JSON.stringify to show a formatted object.

let result = {
    "data": {
        "results": [
            {
                "customerId": 123,
                "firstName": "Name",
                "lastName": "LastName",
                "displayName": "Name LastName",
                "phoneNumber": "4159436367",
                "email": "email@email.com",
                "notes": null,
                "memberNumber": null,
                "highlights": null
            }
        ],
        "total": 1,
        "page": 1
    },
    "error": null
};
console.log(JSON.stringify(result, null, 4));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading