简体   繁体   English

将数据解析为JSON格式

[英]Issue Parsing data to JSON Format

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. 我对编程和开发世界真的很陌生,并且已被分配连接到网站API来解析数据并创建文本文件。 The problem I am encountering is the output [object Object] 我遇到的问题是输出[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). 尝试解析之前得到的是原始数据,但是当我尝试仅执行以下代码时:JSON.parse(Http.responseText)。 I get the following output 我得到以下输出

[object Object]. [对象对象]。

The document.write() function takes parameters of type string. document.write()函数采用字符串类型的参数。 JSON.parse() converts the JSON string to the object format which document.write() cannot understand. JSON.parse()将JSON字符串转换为document.write()无法理解的对象格式。 So it prints the typeOf(data) insted. 因此,它会打印插入的typeOf(data) The result of typeOf(data) is a string which is [Object object] so [Object object] is printed. typeOf(data)的结果是一个字符串,该字符串是[Object object]因此将打印[Object object]

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

You can refer the docs on MDN which states that it takes in parameters of string type. 您可以参考有关MDN的文档,其中指出该文档接受字符串类型的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM