簡體   English   中英

我正在嘗試將數據轉換為 JSON 格式,我得到了 JSON.parse() 錯誤

[英]I am trying to convert data into a JSON format and I am gettiing a JSON.parse() Error

我收到語法錯誤:“在 IncomingMessage 的 JSON.parse () 處的 JSON 輸入意外結束。”。 我不知道為什么我會收到這個錯誤。

這是我的代碼:

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

 app.get("/", function(req, res){
const url = "http://api.openweathermap.org/data/2.5/forecast?q=Accra&id=524901&appid=18a15324259a5d6f30f8e6610f8a4310";
https.get(url, function(response){
 
    response.on("data", function(data){
        const weatherData = JSON.parse(data);
        console.log(weatherData);
    //    console.log(data);
    });
  });
});

在這里,您嘗試在確認數據是否已完全收到之前獲取數據。
而不是在 on('data') 處讀取,而是等待 on('end') 類似這樣的內容:

    body = [];  
    req.on('data', (chunk) => {

        // Storing the chunk data
        body.push(chunk);
    });

    req.on('end', () => {

        // combining and parsing the chunk data to normal data
        const parsedBody = Buffer.concat(body).toString();
        const message = parsedBody.split('=')[1];
        // Now you can parse the **message** to find the data
        console.log(JSON.parse(message))
    });

這將在收集所有塊后收集並解析一次數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM