Json don't allow single quotes, to fix the input you must change the character to double quote, for example str.replace(/'/g, '"')
How to handle single quote in the JSON string
I have created a class with list of properties where one of the property contains name which contains single quote. But when I serialize the object using JSON ( JsonConvert.SerializeObject) SerializeObjec and pass it to the Page.ClientScript.RegisterClientScriptBlock(.. where I am getting an error missing argument )
customer.CustomerID = Convert.ToString(Session["Number"]);
customer.CustomerName = Convert.ToString(Session["Name"]);
customer.Type = type;
customer.InvoiceFromDate = Convert.ToString(Session["From_Date"]);
customer.InvoiceToDate = Convert.ToString(Session["To_Date"]);
string output = JsonConvert.SerializeObject(customer);
Page.ClientScript.RegisterClientScriptBlock(GetType(), "SaveInfo", "SetData('" + output + "','" + URL + "');", true);
In the above customer.CustomerName contains value = "The Young's Family"
Any help is appreciated
3 answers
Sort by: Most helpful
-
-
Timon Yang-MSFT 9,591 Reputation points
2021-08-25T02:05:50.407+00:00 Is there an exception in line 7?
There is a single quote in my example, but I didn't encounter this problem.
class Program { static void Main(string[] args) { MyClass myClass = new MyClass() { ID = 1, Name = "TimonYang's Name" }; var re = JsonConvert.SerializeObject(myClass); MyClass myClass1 = JsonConvert.DeserializeObject<MyClass>(re); } } class MyClass { public int ID { get; set; } public string Name { get;set; } }
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread. -
Bruce (SqlWork.com) 68,306 Reputation points
2021-08-25T02:20:25.557+00:00 you issue is not the JSON which support unquoted single quotes, but that you render in a javascript string literal.
for simplicity assume:
var output = "The Young's Family";
then
"SetData('" + output +"')"
renders as:
SetData('The Young's Family')
but because you used single quotes to the start the literal, you must quote:
SetData('The Young\'s Family')
therefore, in your output variable replace all "'" with "\'".
output = output.Replace("'","\'"));
note: need to escape \ in c#