PDA

View Full Version : Problem with embedded quotes and backslashes in JSON



hornfrog
8 Jun 2011, 2:59 PM
I have an ext data store using the ajax proxy and a JSON reader. It points to a server process that is returning text containing backslashes and quote characters. They are being encoded on the server, so the outgoing string is something like this:

{
"myRoot": [
{
"field1": "2",
"field2": "ABC",
"field3": "1/1/2011 12:00:00 AM",
"field4": "this has \"quote\" characters",
"field5": "c:\\temp\\myfolder"
}
]
}

The problem is that when it gets to the Ext, the result is already decoded, so the JSON decoder throws an error. In Firebug that reads something like

Ext.Error: You're trying to decode and invalid JSON String: {"myRoot": [{"field1": "2","field2": "ABC", "field3": "1/1/2011 12:00:00 AM","field4": "this has "quote" characters","field5": "c:\temp\myfolder" }]}

The response is already decoded. Does anyone have an answer for handling this situation? Is decoding occurring in the ajax proxy prior to JSON decoding, and can that be turned off?

Thanks.

hornfrog
9 Jun 2011, 3:00 PM
I found a workaround, but it isn't pretty...

BTW, this is with C# and ASP.NET

On the server, when building up the json return string, use another unused character besides a quote (") to delimit the field names and values. I used the tilde character (~).

Next, use an encoder, such as the System.Web.HttpUtility.JavaScriptStringEncode method to encode the field values. Using the example originally posted, a piece of the result would look something like this:

~field4~:~this has \"quote\" characters~

Next, once the entire json result has been put together, encode the whole thing again using the same encoder. That gives you something like this:

~field4~:~this has \\\"quote\\\" characters~

Finally, replace the tildes (or whatever character you use) with a quote so that the final result contains this:

"field4":"this has \\\"quote\\\" characters"

Do a Response.Write on that and it will work in ExtJs with the json decoder.

Basically what I'm doing is double encoding the field data. It's ugly, but seems to work.

Any better ideas would be welcome.

skirtle
10 Jun 2011, 7:55 PM
That shouldn't be necessary.

Can you use Firebug or similar to confirm that the JSON data transferred over the wire really does contain the slashes? Also, both Firebug and the Chrome Developer Tools have a 'JSON' tab to view the decoded JSON data (confirming it is valid) but you'll need to set a suitable content-type to get Firebug to show that tab.

How are you then loading the data into the store?