【问题标题】:JSON.parse issue in Node.jsNode.js 中的 JSON.parse 问题
【发布时间】:2017-02-16 06:37:25
【问题描述】:

我正在对返回简单 JSON 对象的 url 执行 get 请求。

这里是网址:http://live.albiononline.com/status.txt

如您所见,它是一个文本文件,它的内容类型标头是 text/plain。当我收到正文日志时,它是:

{ "status": "online", "message": "All good." }

但是当我尝试记录时,body.status 它是未定义的。当我做var data = JSON.parse(body); 然后console.log(data.status); 我得到:

undefined:1
{ "status": "online", "message": "All good." }
^

SyntaxError: Unexpected token  in JSON at position 0

知道发生了什么吗?我认为这与它从 .txt 文件中提取的事实有关?

更新:

request('http://live.albiononline.com/status.txt', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body); // { "status": "online", "message": "All good." }
                console.log(body.status); // undefined
            }
        });

【问题讨论】:

  • 已经是 JSON 对象了。你不需要解析
  • 在我的问题中我说,'但是当我尝试记录时,body.status 它是未定义的。'
  • 你能给我看看你的代码吗
  • 向问题添加代码
  • 试试JSON.parse(JSON.stringify(body)).status

标签: javascript json node.js api


【解决方案1】:

原因是因为输出的不是字符串化的 JSON 对象,只是普通的字符串。

我在处理您的示例代码时得到的输出:

'{ "status": "online", "message": "All good." }\r\n'

真正的 JSON 字符串末尾不会有多余的空格和转义字符。

解决方案:

x=x.trim(); // trimming off the \r\n
var output = JSON.parse(x); // parsing the JSON

【讨论】:

  • 嗯。那么如何将其解析为对象呢?
  • 这就是答案,在 JSON.parse() 之前剪掉 \r\n
  • 你是救生员。非常感谢!
猜你喜欢
  • 2016-03-27
  • 2011-09-23
  • 2014-07-06
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 2016-05-18
相关资源
最近更新 更多