JSON.stringify() - Escaping Issue

青春壹個敷衍的年華 提交于 2019-12-23 04:04:28

问题


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:


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



来源:https://stackoverflow.com/questions/19774626/json-stringify-escaping-issue

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