Can Json have a XSS bug?

Yes, there are potential XSS issues with JSON too. For one thing, if your client-side code uses the JSON contents to update the DOM, you might end up with a Client XSS vulnerability.

Also, some browsers have been known to be too “smart” about rendering contents in a user-friendly way, which has led to XSS issues. It is therefore recommended to set the “X-Content-Type-Options: nosniff” header in JSON responses. Even if your API is only intended to be used via AJAX, you need to protect users who might end up accidentally (or being tricked into) loading the JSON in a browser page.

Finally, you are talking about a database field being ‘invalid’. Remember the first rule of XSS prevention: don’t sanitize input (e.g. before inserting into your DB) but sanitize output. The exact escaping requirements depend on the output context, so the same DB field used in HTML, CSS or JSON would require different escaping. So the DB field cannot be inherently ‘invalid’, only the way you render it.

6 Likes