Tutorial :Javascript: Escape " from json string


I've got a bit of a problem. I'm currently working on converting an old system to a newer version. In the old version, data requests were managed by Java applets, which had no problems with the "-char in the data. Now, though, I'm fetching the data from a database and converting it to a JSON-string using XSLT, and then - with the prototype-function .evalJSON() - making the string into an object. The XSL then structure the data like this (example) :

{rowsets: [ { rows: [ { "ID":"xxx","OtherProperty":"yyy" } ] } ] }  

Which in it self is OK. Now,when there's some data in the database containing "-characters, the evalJSON() fails, because it destroys the usually well-formatted JSON string, like this:

{rowsets: [ { rows: [ { "ID":"xxx","OtherProperty":"yyy "more" zzz" } ] } ] }  

Now, what i want to do, is escape the 'unwanted' "-chars somehow - without having to make some kind of Stored Procedure to du it server-side for me. I've tried to wrap my head around a RegEx, but I'm not very experienced in that area, and therefore I'm having a really hard time figuring it out.

If it's any help, the character sequences that are sure to be legal are: [":"] and [","] and the sequences that are likely to appear, and should be escaped, are: [\s"], ["\s], [",], [".] (\s indicates a whitespace)

All kinds of help is appreciated, even if it's some SQL that makes it all a lot easier :)

Thanks in advance!


If you're in XSLT land then you're reinventing the wheel. Google up "badgerfish" and see here for a fairly solid implementation. You may of course have other problems getting in the way, but first things first.


I ended up taking a shortcut, using a string-replace template in my XSL to replace the "-characters with \" before returning the JSON to my javascript function, thus not needing to escape anything client-side.

(Used this: http://geekswithblogs.net/Erik/archive/2008/04/01/120915.aspx)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »