JSON.parse() 出现意外错误:“JSON 输入意外结束”

时间:2021-05-03 16:35:12

标签: node.js json api express https

console.log(d);给出以下输出(十六进制代码):

<缓冲液 7b 22 73 75 63 63 65 73 73 22 3a 74 72 75 65 2c 22 64 61 74 61 22 3a 7b 22 73 75 6d 6d 74 72 75 65 2c 22 64 61 74 61 22 3a 7b 22 73 75 6d 6d 73 2 6 2 6 2 6 3 2 7 2 7 3 2 7 2 39 32 35 36 30 ... 293 更多字节>

<缓冲液 6f 62 61 72 20 49 73 6c 61 6e 64 73 22 2c 22 63 6f 6e 66 69 72 6d 65 64 43 61 73 65 73 64 2 3 6 e 3 6 2 3 6 e 3 6 2 3 6 e 3 6e 66 69 72 6d ... 1319 更多字节> <缓冲器 43 61 73 65 73 49 6e 64 69 61 6e 22 3a 35 39 34 36 30 31 2c 22 63 6f 6e 66 69 72 6d 65 64 437 6 2 6 4 6 2 5 6 4 6 2 5 6 2 5 69 73 ... 1319 更多字节>

<缓冲器 38 2c 22 63 6f 6e 66 69 72 6d 65 64 43 61 73 65 73 46 6f 72 65 69 67 6e 22 3a 33 2c 22 63 6 3 3 6 3 6 3 6 3 6 3 6 3 6 3 36 35 38 2c 22 ... 1319 更多字节>

<缓冲器 61 6c 43 6f 6e 66 69 72 6d 65 64 22 3a 31 32 30 37 31 31 32 7d 2c 7b 22 6c 6f 63 22 3a 66 6 2f 6e 6 16 2 6 e 6 2 6 e 6 66 69 72 6d 65 ... 740 多个字节>

当我尝试使用 JSON.parse(d) 将其转换为 JSON 时,出现以下错误:

未定义:1

{"success":true,"data":{"summary":{"total":19925604,"confirmedCasesIndian":19925556,"confirmedCasesForeign":48,"discharged":16293003,"deaths",218959 "confirmedButLocationUnidentified":0},"unofficial-summary":[{"source":"covid19india.org","total":7945975,"recovered":7198877,"deaths":119538,"active":626192}] ,"regional":[{"loc":"安达曼和尼科巴

SyntaxError: Unexpected end of JSON input

at JSON.parse (<anonymous>)

at IncomingMessage.<anonymous> (E:\Web Development\Test\app.js:16:24)

at IncomingMessage.emit (events.js:315:20)

at IncomingMessage.Readable.read (internal/streams/readable.js:519:10)

at flow (internal/streams/readable.js:992:34)

at resume_ (internal/streams/readable.js:973:3)

at processTicksAndRejections (internal/process/task_queues.js:80:21)

这是我的 app.js 文件代码:

const express = require("express");
const https = require("https");

const app = express();


app.get("/", (req, res) => {

  const url = "https://api.rootnet.in/covid19-in/stats/latest";

  https.get(url, function(response) {
    console.log(response.statusCode);

    response.on("data", (d) => {

      console.log(JSON.parse(d));
      // console.log(d);

    })

  res.send()

  })



})



app.listen(3000, () => {
  console.log("server up and running at port 3000");
})

2 个答案:

答案 0 :(得分:0)

.on("data") 方法接收缓冲区块,接收完成后需要连接缓冲区,转换为字符串,然后解析为 JSON。

https.get(url, function(response) {
    const data = [];
    response.on("data", (d) => {
        data.push(d);
    }).on('end', function() {
        //at this point data is an array of Buffers
        //so Buffer.concat() can make us a new Buffer
        //of all of them together
        const buffer = Buffer.concat(data);
        const obj = JSON.parse(buffer.toString());
        console.log(obj);
    });
})

答案 1 :(得分:0)

即使问题是关于 https

为了让事情更简单,我是否建议使用 node-fetch(和/或 axios)而不是 https,因为它很常用(而且更容易,因为您不必检查 start 或数据结束)。

const fetch = require('node-fetch')

......

const results = await fetch(url).then(res => res.json());
console.log(results)