javascript - JSON 解析抛出的意外 token 错误

标签 javascript json mastercard

需要一些帮助来找出页面加载时抛出的 JSON.parse 错误。

Uncaught SyntaxError: Unexpected token m in JSON at position 0 at JSON.parse ()

这只是 Mastercard 支付网关中提供的示例代码 documentation .我正在尝试使用商家提供的测试数据对其进行测试。我通过验证器运行代码,它没有返回任何错误。

这是我要执行的代码。

<!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>

enter image description here

最佳答案

大多数情况下,当 JSON.parse 抛出位置 0 无效 JSON 的错误时,问题出在 Byte Order Mark (BOM) ( Wikipedia )。

为避免解析 BOM,您应该检查 JSON 字符串是否以 0xFEFF 开头,这是 BOM 的 Unicode 表示,然后手动将其删除。

例子:

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);

关于javascript - JSON 解析抛出的意外 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56823438/

相关文章:

javascript - 如何在 AngularJS 中使用 jQuery

javascript - 使用 javascript 显示测验问题

iphone - SBJson Execptions after parsing (__NSArrayM objectForKey :)

javascript - 我如何创建 : if window. location.origin 不是这个,屏幕分辨率是这个然后重定向 url?与js

javascript - 当页面略长于页面高度时,如何制作一个没有奇怪滚动故障的动态粘性工具栏?

Javascript:对集合中的对象求和

javascript - 对具有数组的 Son 数据进行 Angular ng-repeat

api - 是否有用于创建虚拟信用卡(VCC)的API?

php - 万事达卡支付集成服务无法在 PHP 中运行