【问题标题】:Unable to parse JSON string to object无法将 JSON 字符串解析为对象
【发布时间】:2015-03-28 15:53:00
【问题描述】:

所以我正在尝试从网络服务器(URL:https://api.uwaterloo.ca/v2/codes/subjects.json?key=6eb0182cf11ca581364ccceee87435f4)检索数据。我使用 JSON 验证器确保其有效的 JSON 数据是有效的。

我要做的是获取数据数组中主题键的值。但是,当我第一次尝试将响应解析为 JSON 对象时,它不允许我这样做。

这里是代码sn-p

    var req = https.request('https://api.uwaterloo.ca/v2/codes/subjects.json?key=6eb0182cf11ca581364ccceee87435f4', function(res) {
  //res.setEncoding('utf8');
  res.on('data', function(d) {

    //console.log(Object.prototype.toString.call(d));
    //jsonString = JSON.stringify(d);
    //console.log(jsonString);

    fs.writeFile("./test.txt", d, function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
    });

    jsonObject = JSON.parse(d);

    // console.log(typeof(jsonObject.count));

    // for (var key in jsonObject)
    // {
        // if(jsonObject.hasOwnProperty(key))
        // {
            // console.log(key + "=" + jsonObject[key]);
        // }
    // }

  });

});

req.end();

req.on('error', function(e) {
  console.error(e);
});

我收到以下错误

^
SyntaxError: Unexpected end of input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (C:\Users\Chintu\Desktop\Chaitanya\Study\Term
 4B\MSCI 444\Project\Full Calendar\Trial\helloworld.js:79:20)
    at IncomingMessage.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at IncomingMessage.Readable.push (_stream_readable.js:126:10)
    at HTTPParser.parserOnBody (_http_common.js:132:22)
    at TLSSocket.socketOnData (_http_client.js:310:20)
    at TLSSocket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at TLSSocket.Readable.push (_stream_readable.js:126:10)

感谢任何帮助。

谢谢!

【问题讨论】:

  • 您尝试在获得一些数据后立即解析字符串 (on("data"))。在尝试解析它之前,请确保您拥有完整的响应。您收到多少次“文件已保存!”在控制台中?

标签: javascript json node.js api


【解决方案1】:

您没有在解析之前缓冲全部内容。 data 是针对单个 chunk 发出的,它可能是也可能不是整个响应。

试试这个:

var req = https.get(url, function(res) {
  if (res.statusCode !== 200)
    res.resume(); // discard any response data
  else {
    var buf = '';
    res.on('data', function(d) {
      buf += d;
    }).on('end', function() {
      var result = JSON.parse(buf);
    });
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多