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

2024-01-08

The bodyAuthorize.net 的沙箱 API 的响应是:

{
  "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);
}

我收到此错误:

SyntaxError:JSON 中位置 0 处出现意外标记

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

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

我究竟做错了什么?我想将 JSON 解析为 JS 对象。


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.
byte order mark image
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NodeJS 语法错误:JSON 中位置 0 处出现意外标记 的相关文章

随机推荐