Node.js中的JSON解析错误

时间:2012-03-17 13:54:38

标签: json node.js

Node v0.4.12

var http = require('http');

var options = {
  host: 'example.com',
  port: 80,
  path: 'example.aspx'
};

var req = http.request(options, function(res) {
  var result = '';
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    result += chunk;
  });

  res.on('end', function () {
    var jsonStr = JSON.stringify(result);
    var data = JSON.parse(jsonStr);

    console.log(data['Date']);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.end();

当我尝试console.log(data)时,console.log(data['Date'])会有效undefined

示例JSON方案:

{“Date”:“17.03.2012 15:28:47”,“Categories”:[{“ID”:1,“Name”:“Foo”,“URLSlug”:“foo”}]} < / p>

如何解决此问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果我删除了所有的http请求代码,只是尝试解析并打印出已解析的json的Date部分:

$ cat ex2.js
var data = JSON.parse('{"Date":"17.03.2012 15:28:47", "Categories":[{"ID":1,"Name":"Foo","URLSlug":"foo"}]}');
console.dir(data);
console.log(data['Date']);

$ node ex2.js
{ Date: '17.03.2012 15:28:47',
  Categories: [ { ID: 1, Name: 'Foo', URLSlug: 'foo' } ] }
17.03.2012 15:28:47

$

示例代码工作正常。你在运行你发布的文字代码吗?如果您是,那么错误可能是example.com没有返回您作为example.asp的示例给出的JSON。对我而言:

$ curl -I http://example.com/example.asp
HTTP/1.0 302 Found
Location: http://www.iana.org/domains/example/
Server: BigIP
Connection: Keep-Alive
Content-Length: 0

哪个不是JSON,只是302重定向响应。您可能希望打印出完整的结果,以便查看它是否实际上是JSON或其他东西(在本例中为HTML):

$ cat example.js
var http = require('http');

var options = {
  host: 'google.com',
  port: 80,
  path: '/'
};

var req = http.request(options, function(res) {
  var result = '';
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('got data back!');
    result += chunk;
  });

  res.on('end', function () {
    console.log('request is done');
    console.dir(result);
    var jsonStr = JSON.stringify(result);
    var data = JSON.parse(jsonStr);
    console.log(data['Date']);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.end();

对我而言:

$ node example.js
got data back!
request is done
'<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>301 Moved</TITLE></HEAD><BODY>\n<H1>301 Moved</H1>\nThe document has moved\n<A HREF="http://www.google.com/">here</A>.\r\n</BODY></HTML>\r\n'
undefined

HTH,

凯尔