What is the correct way to return JSON content type?


In this tutorial we are going to explain which is the proper way to return JSON in a http response. We are going to also cover how to return a json from a rest api.

IMPORTANT If you return json as mime-type of text/html, you will have a security issue at your site.

MIME media type for JSON text

(RFC 4627)[http://www.ietf.org/rfc/rfc4627.txt] defines that the MIME media type for JSON text is application/json. When encoding json you must use:

  • 8bit if UTF-8.
  • binary if UTF-16 or UTF-32.

JSONP with callback

JSONP (JSON with Padding) is used to request data from a server residing in a different domain. When using JSONP the content-type should be application/javascript.


What about application/x-javascript

application/x-javascript is an experimental MIME type. RFC 4627 didn't specify anything about this MIME type. Some applications could use x-javascript to compress the json response.

Old internet explorer have issues with application/json

older IE versions choke on this since they expect text/javascript.


A JSON text can be safely passed into JavaScript's eval(). Before using eval you must ensure that all the characters are not enclosed in strings are in the set of characters that form JSON tokens. You can use the following regex to validate if the json is secure or valid:

var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
             text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
         eval('(' + text + ')');