NodeJS SyntaxError:JSON 中的意外标记位于位置 0 [英] NodeJS SyntaxError: Unexpected token in JSON at position 0

查看:105
本文介绍了NodeJS SyntaxError:JSON 中的意外标记位于位置 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Authorize.net 的沙箱 API 响应的 body 是:

The body of the response from Authorize.net's sandbox API is:

{
  "messages": {
    "resultCode": "Error",
    "message": [
      {
        "code": "E00012",
        "text": "You have submitted a duplicate of Subscription 5777085. A duplicate subscription will not be created."
      }
    ]
  }
}

但是当我去解析它时:

try {
   bodyObj = JSON.parse(body);
} catch (ex) {
   console.error(ex);
}

我收到此错误:

语法错误:JSON 中位置 0 处出现意外标记

SyntaxError: Unexpected token in JSON at position 0

还有这个:console.log(response.headers['content-type']);

返回:application/json;charset=utf-8

我做错了什么?我想把 JSON 解析成一个 JS 对象.

What am I doing wrong? I want to parse the JSON into a JS object.

推荐答案

其实你没看到,但是有一个看不见的unicode字符,特别是JSON开头的字节序标记.
由于字节顺序标记不是有效的 JSON 字符,因此 JSON.parse 拒绝了它.

要删除,请使用以下代码.

Actually you didn't see it, but there was a invisible unicode character, specifically the byte order mark at the beginning of the JSON.
Since the byte order mark is not a valid JSON character, JSON.parse rejected it.

To remove, use the following code.

function removeByteOrderMark(str){
    return str.replace(/^\ufeff/g,"")
}
// OR (faster),
let removeByteOrderMark = a=>a[0]=="\ufeff"?a.slice(1):a

这篇关于NodeJS SyntaxError:JSON 中的意外标记位于位置 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆