0

I have a JSON string

var str = '{'+
            '"name": "John Doe",'+
            '"company": [{"name": "ABC Corp"}, {"name": "XYZ Corp"}],'+
            '"salary": "$200000"'+
           '}';

I make the ajax call as

$.ajax({
     url: 'url',
     type: 'POST',
     context: document.body,
     dataType: 'json',
     data: str,
     success: function(data){},
     error: function(error){}
     });

How can I escape the double quotes inside the JSON array before making the ajax call.

user544079
  • 16,109
  • 42
  • 115
  • 171

2 Answers2

2

str is already valid JSON (according to JSONLint), so you don't need to escape anything before sending it via $.ajax.

SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • wait - so for the data option - you can just pass in a string like "test"? I thought it had to be key/value like `"key=test"(as string)` or `{key:test} <-- as object` – wirey00 Apr 02 '14 at 20:04
  • 2
    @ᾠῗᵲᄐᶌ - You can send a string formatted as json to `$.ajax`. You probably shouldn't but thats a different discussion. – Jamiec Apr 02 '14 at 20:05
  • @Jamiec hmm.. never knew that - will have to check out the code – wirey00 Apr 02 '14 at 20:06
2

It looks like you're going the wrong way - JSON.stringify is used to turn a JSON object to a string, the method you want is JSON.parse.

So change that to:

$.ajax({
     url: 'url',
     type: 'POST',
     context: document.body,
     dataType: 'json',
     data: JSON.parse(str),
     success: function(data){},
     error: function(error){}
     });

You can also pass a string formatted as JSON to $.ajax and as your string was already valid JSON you could just skip that step entirely:

$.ajax({
     url: 'url',
     type: 'POST',
     context: document.body,
     dataType: 'json',
     data: str,
     success: function(data){},
     error: function(error){}
     });

Although you could just build it up as an object to start with if that is easier (It often is than trying to format a string!):

var postData = {
   name:'John Doe'
   ... etc
};

$.ajax({
     url: 'url',
     type: 'POST',
     context: document.body,
     dataType: 'json',
     data: postData,
     success: function(data){},
     error: function(error){}
     });
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Why would you parse it if it's a valid string, you can't send an object so jQuery would have to stringify it back again internally ? – adeneo Apr 02 '14 at 19:59
  • @adeneo - Im just answering the question as stated. I was updating with a better solution when you made that comment. – Jamiec Apr 02 '14 at 20:00
  • 1
    You should note that passing a JSON string will gives a completely different result than passing a JavaScript object. – Musa Apr 02 '14 at 20:43