6

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?

1
  • 4
    Since you're giving Angular an Object with its data option in the 2nd snippet, the values are being double-encoded – once by you and once by $http. Your use of JSON.stringify() likely isn't necessary. Commented Mar 2, 2016 at 6:26

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

6 Comments

No, I have other properties in the same data object where in every property of string type. Thus the Values object need to be sent as a string.
If you have to send it as string. Then you have to json_decode it at the server, to get an object again.
@RamaRaoM If the value of "Values" needs to be a string, then the backslashes are necessary to distinguish which double-quotes are characters in the string (with backslash) and which are syntax (string literal delimiters). That's unavoidable.
@JonathanLonowski Then where should the slashes be removed? At server end?
@JonathanLonowski As we see the example, the Values object is stringified only once. I guess $http is stringifying the total data object one more time.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.