首页 > 解决方案 > 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>

在此处输入图像描述

标签: javascriptjsonmastercard

解决方案


大多数情况下,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);

推荐阅读