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

3
  • Why not use jQuery with an object, or the JSON package? Commented Mar 4, 2013 at 9:40
  • Put the data in quotes and escape all quotes in the data. Commented Mar 4, 2013 at 9:40
  • how to escape the quotes in this case. Commented Mar 4, 2013 at 9:45

4 Answers 4

2

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

var jsonString = JSON.stringify( Data );
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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);

1 Comment

Is JSON.stringify supported on all the browsers?
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

1 Comment

You forgot to escape the quotes.

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.