JSON.stringify() - Escaping Issue

2019-06-06 04:40发布

I am currently using AJAX with JQuery to send json to an API server. However, there seems to be an issue with a server that is escaping the JSON string when I use JSON.stringify() but on another server when using the exact same code it works without any problems.

Here is an example of the Javascript object that I am using stringify on:

{"jsonrpc":"2.0","method":"get_contacts","params":["4345ert343t34t34t4e564",
{"campaigns":["AI5D"]}],"id":1} 

I am working from the examples here https://github.com/GetResponse/DevZone/blob/master/API/examples/javascript_synopsis.html

On one server the double quotes are being escaped with a backslash which is causing the API server to respond with a parse error as this is obviously incorrect. On a different server the escaping is not present and the API works fine. The exact same code is being used on both servers.

Does anybody have any idea what could be causing this? Could it be an encoding issue? One thing to note is that on one server I have to enter the JavaScript via a WYSIWYG editor but the JavaScript appears to display correctly on page load.

If anybody has any ideas that would be great as I have spent a long time trying to figure this out.

EDIT:

Here is the JS code that I am using:

var api_key = '4345ert343t34t34t4e564';
var api_url = 'http://api2.getresponse.com';            
var CAMPAIGN_ID = 'AI5D';

var data = JSON.stringify({
"jsonrpc"   : "2.0",
"method"    : "get_contacts",
"params"    : [
        api_key,
        {
            "campaigns" : ["AI5D"] 
        }
    ],
"id"        : 1
});

console.log(data);

jQuery.ajax({
    url         : api_url,
    data        : data,
    type        : "POST",
    contentType : "application/json",
    dataType    : "json",
    crossDomain : true,
    async       : true,
    success     : function(response) 
    {                        
        alert(JSON.stringify(response));
        console.log(JSON.stringify(response));
    }

1条回答
姐就是有狂的资本
2楼-- · 2019-06-06 05:47

I have discovered the solution to the problem!

It appears that an old version of Mootools in the header (v.1.2.4) was causing a conflict with JSON.stringify(). Removing the old Mootools library fixes the issue.

Apparently Mootools v1.2.4 tries to override JSON.stringify() with it's own alterations which are incorrect and in turn causes the issue with the backslash escaping. This issue was found here http://outsourceror.blogspot.co.uk/2011/04/mootools-intrudes-on-native-json-and.html

Updating Mootools to the latest version should also fix this http://mootools.net/download

查看更多
登录 后发表回答