javascriptjsonmocha.jswdio

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 }

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));