ViVi ViVi - 3 years ago 226
ASP.NET (C#) Question

While parsing JSon data getting Error "Uncaught SyntaxError: Unexpected token x in JSON at position"

I am using c# to serialize some data to

JSON
and sending it to javascript using below code :

string serializedDS = JsonConvert.SerializeObject(ftpd);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", string.Format("Func('{0}');", serializedDS), true);


The output of
JsonConvert.SerializeObject(ftpd)
is
{"FTPUserName":"XKK\\xpuser1","FTPPassword":"xpr@fr@12","FTPServerAddress":"255.255.255.0","FTPPath":"In/Files"}


My javascript function :

function Func(serializedDS) {
var result = JSON.parse(serializedDS);
if (result != null)
{
var a = result["FTPUserName"];
var b = result["FTPPassword"];
var c = result["FTPServerAddress"];
var d = result["FTPPath"];

}
}


The data recevied as function argument is
serializedDS = "{"FTPUserName":"XKK\xpuser1","FTPPassword":"xpr@fr@12","FTPServerAddress":"255.255.255.0","FTPPath":"In/Files"}"


But at the line
var result = JSON.parse(serializedDS);
I am getting this error
Uncaught SyntaxError: Unexpected token x in JSON at position 20
at JSON.parse (<anonymous>)


Any help would be appreciated!

Answer Source

The issue is caused by 2 backslashes. I have changed the Func to deal with Json object directly.

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", string.Format("var result = {0}; setData();", serializedDS), true);

In javascript create the below function.

function setData() {

if (result != null)
{
    var a = result["FTPUserName"];
    var b = result["FTPPassword"];
    var c = result["FTPServerAddress"];
    var d = result["FTPPath"];

}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download