Tuesday, May 29, 2012

correct HTTP header for json file

I've searched around and found two different ways to define Content-type for JSON file loaded with php.

header('Content-type: text/json');
header('Content-type: application/json');

which one should be used ?

Source: Tips4all


  1. AFIK IANA has officially registered a MIME type for JSON as application/json in RFC4627, also is listed in the Internet Media Type list.

  2. Look at things like the Apache Axis spec. They favor application/json.

  3. application/json is favored but usually web browsers don't know what to do with those headers and screws it up. For stuff like jquery, I have seen text/html recommended. If you are having errors pop up (e.g. download dialog box) then try text/html

  4. I recently had a very strange run in with this.

    I had a form which used jQuery to do an AJAX lookup against a PHP script, and then return the response as JSON, formed using PHP's json_encode() function.

    It was all working fine for a couple of months, then this morning it stopped working... It turns out the javascript couldn't parse the JSON correctly.

    My original method used eval.


    var p = eval('(' + msg + ')');

    But that gave me the error:

    missing ] after element list

    I then tried using

    var p = JSON.parse(msg);

    Using the json2.js library from http://json.org. This also failed.

    I checked my JSON was formatted correctly using an online tool - it was.

    In the end I tried changing the header type I was setting in the PHP script which was being called by jQuery AJAX.

    I changed it from application/json to text/plain

    And both the eval() and the JSON.parse solutions immediately worked... Much to my relief as I was running out of ideas.

    Very odd and still don't know quite why, but thought I'd post here in case someone runs into a similar issue, or anybody can provide an explanation.