Issue Parsing data to JSON Format

Viewed 58

I am really new to programming and development world and have a been assigned is to connect to a website API to parse data and create a text file. The problem I am encountering is the output [object Object]

const Http = new XMLHttpRequest();
const url='https://api.random.com?key=12346DD-7412-45A6-X4E5-B5D2-45D2983DF12E'; (Dummy Key)
Http.open("GET", url);
Http.send();

Http.onreadystatechange=function() {
    if(this.readyState==4 && this.status==200) {
        const data = JSON.parse(Http.responseText);
        document.write(data);
    }
}

What I get before attempting to parse is the raw data but when I try to just the following code: JSON.parse(Http.responseText). I get the following output

[object Object].

1 Answers

The document.write() function takes parameters of type string. JSON.parse() converts the JSON string to the object format which document.write() cannot understand. So it prints the typeOf(data) insted. The result of typeOf(data) is a string which is [Object object] so [Object object] is printed.

Use document.write(JSON.stringify(data));

You can refer the docs on MDN which states that it takes in parameters of string type.

Related