How to solve JSON Syntax error. How to get response?

不羁岁月 提交于 2019-12-24 07:45:17

问题


This is the UPS shipping webservices API. I am getting this error :

{"Error":{"Code":"4","Description":"JSON Syntax error"}}

AJAX Code:

  <script>          
        var formData = { "UPSSecurity": { "UsernameToken": { "Username":"xxx.com", "Password":"xxxxx" }, "ServiceAccessToken": { "AccessLicenseNumber":"1234D567DF67" } }, "RateRequest": { "Request": { "RequestOption":"Rate", "TransactionReference": { "CustomerContext":"Test saran" } }, "Shipment": { "Shipper": { "Name":"Saravanan", "ShipperNumber":"Y72A41", "Address": { "AddressLine":["2311 York Rd"], "City":"Sebastopol", "StateProvinceCode":"CA", "PostalCode":"95473", "CountryCode":"US" } }, "ShipTo": { "Name":"ShipToName", "Address": { "AddressLine":["195 N main st"], "City":"Sebastopol", "StateProvinceCode":"CA", "PostalCode":"95472", "CountryCode":"US" } }, "ShipFrom": { "Name":"ShipFromName", "Address": { "AddressLine":"2311 York Rd", "City":"Sebastopol","StateProvinceCode":"CA", "PostalCode":"95473", "CountryCode":"US" } }, "Service": { "Code":"03", "Description":"Express" }, "Package": { "PackagingType": { "Code": "02", "Description": "Rate" }, "Dimensions": { "UnitOfMeasurement": { "Code": "IN", "Description": "inches" }, "Length": "7", "Width": "5", "Height": "2" }, "PackageWeight": { "UnitOfMeasurement": { "Code": "Lbs", "Description": "pounds" }, "Weight": "10" } }, "ShipmentRatingOptions": { "NegotiatedRatesIndicator": "" } } } };

        $.ajax({
            type       : "POST",
            url        : "https://wwwcie.ups.com/rest/Rate",
            crossDomain: true,
            timeout    : 240000,
            data       : formData,
            dataType   : 'json',
            success    : function(response) 
            {
                alert("result="+response);
            }  
        }); 

    </script>

I don't know where I am wrong. But this request is running perfectly by "POST MAN" and "ARC" tools. Please update answer.


回答1:


You're not sending JSON; jQuery's default serialization when you give it an object is URI-encoding. To send JSON instead, convert your object to a string with JSON.stringify. You should also identify that what you're sending is JSON using contentType, so:

contentType: 'application/json',
data       : JSON.stringify(formData),


来源:https://stackoverflow.com/questions/40084851/how-to-solve-json-syntax-error-how-to-get-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!