javascript - JSON 解析引发的意外令牌错误
问题描述
需要一些帮助来找出页面加载时引发的 JSON.parse 错误。
未捕获的 SyntaxError:JSON.parse () 位置 0 处的 JSON 中的意外标记 m
这只是 Mastercard 支付网关文档中提供的示例代码。我正在尝试使用商家提供的测试数据对其进行测试。我通过验证器运行代码,它没有返回任何错误。
这是我要执行的代码。
<!DOCTYPE html>
<html>
<head>
<script src="https://test-gateway.mastercard.com/checkout/version/52/checkout.js"
data-error="errorCallback"
data-cancel="cancelCallback">
</script>
<script type="text/javascript">
function errorCallback(error) {
console.log(JSON.stringify(error));
}
function cancelCallback() {
console.log('Payment cancelled');
}
Checkout.configure({
"merchant" : "TEST",
"order" : {
"amount" : 1000,
"currency" : "USD",
"description" : "Ordered goods" ,
"id" : 123
},
"interaction" : {
"operation" : "AUTHORIZE",
"merchant" : {
"name" : "ABC Hotel" ,
"address" : {
"line1" : "some road" ,
"line2" : "some city"
}
}
}
});
</script>
</head>
<body>
...
<input type="button" value="Pay with Lightbox" onclick="Checkout.showLightbox();" />
<input type="button" value="Pay with Payment Page" onclick="Checkout.showPaymentPage();" />
...
</body>
</html>
解决方案
大多数情况下,JSON.parse
在位置 0 处抛出无效 JSON 错误时,问题是Byte Order Mark (BOM)
(维基百科)。
0xFEFF
为避免解析 BOM,您应该检查 JSON 字符串是否以 Unicode 表示形式开头,BOM
然后手动将其切断。
例子:
let json = `{"hello":"world"}`;
// make sure you trim the JSON string before, otherwise the first character may be a whitespace
if (json.trim().charCodeAt(0) === 0xFEFF) {
json = json.slice(1); // cut the BOM character
}
const result = JSON.parse(json);
推荐阅读
- python-3.x - 如何在project1中导入一个project2的类?
- c++ - 在比较两个字符串时,如何在不使用类或库的情况下找到字符串数组中的第一个字符?
- reactjs - 如何在列表 React 中推送路由 onClick
- windows - docker 镜像构建卡住了
- cypress - 赛普拉斯检查元素是否有滚动条可见
- javascript - 如何修复'在反应js中带有复选框的带有回车键的按键'
- rest - 使用 ServiceNow 表单进行出站邮寄电话
- java - handleWindowVisibility:令牌 android.os.BinderProxy 没有活动
- sql - 带有“not in”的 SQL 查询非常慢
- apache-spark - 为什么在向量的 Spark 数据帧上进行 MergeSort 连接后的不同计数会给出不确定的结果