0
  var jsonString ="{ "
            jsonString += "name:" + Data.name+",";
            jsonString += "surname:"+ Data.surname+",";
            jsonString += "Address: " + Data.add;
            jsonString += "}"

I am creating following json string for the Ajax call.but when there is "," in the address field. it is giving me error. can anybody tell me proper way to create json string in javascript for ajax calls

iRunner
  • 1,472
  • 6
  • 25
  • 40

4 Answers4

2

Use JSON.stringify() to generate your JSON string. It will automatically escape any character, where this is needed.

var jsonString = JSON.stringify( Data );
Sirko
  • 72,589
  • 19
  • 149
  • 183
1

Please use JSON.stringify():

var jsonString = JSON.stringify({
  'name': Data.name,
  'surname': Data.surname,
  'address': Data.add
});

Please note that @Sirko provided very similar answer. Please use his if you want to serialize all fields from 'Data' object. If not, use mine.

kamituel
  • 34,606
  • 6
  • 81
  • 98
0

Why would you create a json string like that in JavaScript? JSON or "JavaScript Object Notation". You can create an object and make it a JSON string with the built-in methods.

var data = {
  name: Data.name,
  surname: Data.surname,
  ...
};

var json = JSON.stringify(data);
elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

Try this:

var jsonString ="{ ";
jsonString += "name:" + '"'+Data.name + '",';
jsonString += "surname:"+ '"'+ Data.surname + '",';
jsonString += "Address: " + '"'+ Data.add + '"';
jsonString += "}";

or you can use JSON.stringify() from: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106