Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON stringify is adding backslashes

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?

like image 261
Rama Rao M Avatar asked Mar 02 '16 06:03

Rama Rao M


1 Answers

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.

like image 79
Kordi Avatar answered Sep 30 '22 06:09

Kordi