简体   繁体   English

解析文件时,JSON 中位置 0 处出现意外标记 g

[英]Unexpected token g in JSON at position 0 when parsing a file

https.get('example.com/phpfilethatechoesandimtryingtograbtheecho.php', (res) => {
   console.log('statusCode:', res.statusCode);
   onsole.log('headers:', res.headers);

   res.on('data', (d) => {
       return msg.reply(JSON.parse(d));
   });

}).on('error', (e) => {
   throw e;
});

I am trying to grab the echo from that php website.我正在尝试从该 php 网站获取回声。 I tried Express with app.get() but it couldn't console.log().我用 app.get() 尝试过 Express,但它不能使用 console.log()。 I don't know why it didn't error anything with Express but couldn't output.我不知道为什么它没有用 Express 出错但无法输出。

This thing I'm searching answer for works when I output the "d" using process.stdout.write() .当我使用process.stdout.write()输出“d”时,我正在寻找答案。 By "d" I mean the d that is here res.on('data', (**d**)) . “d”是指这里的 d res.on('data', (**d**))

I also managed to get this {"type":"Buffer","data":[103,75,68,101,54,78,109,77,117,65,83,67,52,86,81,88,113,106,101,81,77,86,71,66,90,68,112,100,71,76,103,51]} when I stringified the "d" and replied to my message on Discord.我也设法得到这个{"type":"Buffer","data":[103,75,68,101,54,78,109,77,117,65,83,67,52,86,81,88,113,106,101,81,77,86,71,66,90,68,112,100,71,76,103,51]}当我将“d”字符串化并在 Discord 上回复我的消息时。

The res in your https.get is a Stream. https.getres是一个流。 Now stream has multiple events, data is one of them.现在流有多个事件, data就是其中之一。 When you listen for data event what you get is a chunk of data .当您侦听data事件时,您得到的是一个数据块

So for a JSON file that you are getting from your server (in this case your php file) d is part of it not all of it.因此,对于您从服务器获取的 JSON 文件(在本例中为您的 php 文件), d是其中的一部分,而不是全部。

There is one more event called end , which is, to put it simply, fired when there is no data left in the stream (means all of the data is sent to you).还有一个叫做end事件,简单地说,当流中没有数据时触发(意味着所有数据都发送给你)。 So you need to use end event to actually process the data as all of the data is there with you now.所以您需要使用end事件来实际处理数据,因为所有数据现在都在您身边。

I am adding a code snippet that might help you:我正在添加一个可能对您有帮助的代码片段:

https
  .get("url", res => {
    console.log("statusCode:", res.statusCode);
    console.log("headers:", res.headers);
    let responseData = "";
    res.on("data", d => {
      //store the chunks in a variable
      responseData += d;
    });
    res.on("end", () => {
      //here now you have all the data, so parse the data
      msg.reply(JSON.parse(responseData));
    });
  })
  .on("error", e => {
    throw e;
  });

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

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