I am designing a Web API which returns JSON as the content-type, the response body could contain characters like '
, "
, <
and >
, they are valid characters in JSON. So, my question is should I do HTML encode for my Web API response body or should I leave this task to HTML client who is consuming my Web API?
So if you are intending to write JSON into the html as part of Javascript (a very common use), you need to encode JSON contents to HTML unfortunately. It's much better to avoid this and download data separately. those are some very good points!
HTML encoding ensures that text will be correctly displayed in the browser, not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as an opening or closing bracket of an HTML tag.
The Encoding API provides a mechanism for handling text in various character encodings, including legacy non-UTF-8 encodings. The API provides four interfaces: TextDecoder , TextEncoder , TextDecoderStream and TextEncoderStream . Note: This feature is available in Web Workers.
Any time you are trying to output data that could include untrusted html, you should use HTMLENCODE . Encodes text and merge field values for use in HTML by replacing characters that are reserved in HTML, such as the greater-than sign ( > ), with HTML entity equivalents, such as > .
No; you must not.
You must only escape data if and when you concatenate it into a structured format.
If you return JSON like { "text": "Content by X & Y" }
, anyone who reads that JSON will see the literal text &
.
It will only work correctly for extremely broken clients who concatenate it directly into their HTML without escaping.
In short:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With