Json string parsing issue
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
Use JSON.stringify()
to generate your JSON string. It will automatically escape any character, where this is needed.
var jsonString = JSON.stringify( Data );
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.
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);
链接地址: http://www.djcxy.com/p/46282.html
上一篇: 将对象键值对转换为JSON
下一篇: Json字符串解析问题