couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Rafał Pocztarski <r.pocztar...@gmail.com>
Subject Re: Best Way to Handle Inserting HTML Data
Date Wed, 17 Nov 2010 04:05:25 GMT
2010/11/17 Matthew Woodward <matt@mattwoodward.com>:
> myJSONString = '{"foo":"bar", "baz":"<a href="http://foo.com">Here's a
> hyperlink</a>"}';
>
> So if I don't do any sort of escaping the first " in the href will cause the
> JSON to be invalid. But whereas I can change " to &quot; in regular text
> (e.g. "Here's a quote" can become &quot;Here's a quote&quot; and still be
> fine), that won't really work with hyperlinks since <a href=&quot;
> http://foo.com&quot;> won't work properly I don't believe, or at any rate
> isn't all that desirable.
>
> If I escape the " with \ (using the example above, this becomes <a href=\"
> http://foo.com\">) that lets me get the document into Couch successfully,
> but I have a feeling that isn't going to work if I just want to display that
> field as HTML on a web page (though I have yet to experiment with that to
> see what happens when it's rendered).

I'll just add to what others have already said that no matter what,
why and how you escape, whether manually or automatically, what should
happen is to always escape once what gets in and then always unescape
once what gets out. (I say "once" because it's easy to escape
something twice and unescape once or vice versa and have a problem.)

I say it because you worry that escaped strings might not work in HTML
but it would be true only if you forget to unescape them when you get
them out and you have to do it anyway when you decode JSON.

The correct way to store any text in JSON is to always escape the
double quote, backslash and control characters (" as \", \ as \\ etc.)
and the correct way to decode strings in JSON is to unescape
everything that starts with backslash - see http://json.org/

It's easy to get it wrong so that's why I second Jonathan's advice to
use a ready JSON encoder/decoder library and not worry about it
yourself.

By the way, I'm new on this list so hello to everyone.

Best regards,
Rafał Pocztarski.

Mime
View raw message