JSON stringify is adding backslashes

Rama Rao M picture Rama Rao M · Mar 2, 2016 · Viewed 7.2k times · Source

When the stringified string is sent to request directly, it is not getting added any slashes.

    var data = { "A": "Aa", "B": "Bb", "C": "Cc" }; // This is JSON object
        data = JSON.stringify(data); // Getting stringified
    var obj = {method: "POST", 
               url: 'http://..XX..XXX.....com',
               data: data // String is being sent as it is
              };
   $http(obj);// Have no slashes added
//Output: {"A":"Aa","B":"Bb","C":"Cc"}

But if the stringified string is set value as property of object and object is sent to server, the string is having backslashes.

        var data = { "A": "Aa", "B": "Bb", "C": "Cc" };
            data = JSON.stringify(data);
        var obj  = {method: "POST", 
                   url: 'XXX',
                   data: { // String is being sent as a value of object property "Values"
                       "Values": data 
                      }
                  };
       $http(obj);//Slashes are added

//output: {"Values":"{\"A\":\"Aa\",\"B\":\"Bb\",\"C\":\"Cc\"}"}

Can somebody take a look once?

Answer

Kordi picture Kordi · Mar 2, 2016

If you stringify its the right behaviour. Cause now it's not an object anymore. Why not sending it complete to the server like this. Data could be a string or an object

var data = { "A": "Aa", "B": "Bb", "C": "Cc" };
var obj  = {method: "POST", 
               url: 'XXX',
               data: data
              };
$http(obj);

If you have to send it as string. Then you have to json_decode it at the server.