[json] What is the correct JSON content type?

I've been messing around with JSON for some time, just pushing it out as text and it hasn't hurt anybody (that I know of), but I'd like to start doing things properly.

I have seen so many purported "standards" for the JSON content type:

application/json
application/x-javascript
text/javascript
text/x-javascript
text/x-json

But which one is correct, or best? I gather that there are security and browser support issues varying between them.

I know there's a similar question, What MIME type if JSON is being returned by a REST API?, but I'd like a slightly more targeted answer.

This question is related to json http-headers content-type

The answer is


The right content type for JSON is application/json UNLESS you're using JSONP, also known as JSON with Padding, which is actually JavaScript and so the right content type would be application/javascript.


The correct answer is:

Content-Type: application/json

If you're calling ASP.NET Web Services from the client-side you have to use application/json for it to work. I believe this is the same for the jQuery and Ext frameworks.


Only when using application/json as the MIME type I have the following (as of November 2011 with the most recent versions of Chrome, Firefox with Firebug):

  • No more warnings from Chrome when the JSON is loaded from the server.
  • Firebug will add a tab to the response showing you the JSON data formatted. If the MIME type is different, it will just show up as 'Response content'.

If the JSON is with padding then it will be application/jsonp. If the JSON is without padding then it will be application/json.

To deal with both, it is a good practice to use: 'application/javascript' without bothering whether it is with padding or without padding.


A part of your question is relevant to me as I just came across it.

A third-party provider is providing a REST service that is used by multiple clients. It's a straight-forward REST called with query parameters that returns a well-formed JSON. I have tested it with PHP and Java where it worked as expected.

My client uses Oracle Service Bus as a gateway between his application server and the Internet. When I made the OSB service, it crashed with an Invalid message format error. Turned out that the content-type being returned was text/html. OSB treats responses as per this header; converting between text, XML and JSON. In this case, the response was JSON but the header didn't say so. Contacting the provider, I got the reply: "We're not going to change it as it doesn't effect anyone else".

The Content-Type header specifies what the content should be, not what it actually is. That is to say, in your consuming program, it's up to you to check or ignore it and process the content in any manner. Another example, you can return GIF data but specify the content type as JSON, then go ahead and ignore the header and read the image data. This won't hurt your program, but may hurt others.

Moral of the story: Play nice.


If you're calling ASP.NET Web Services from the client-side you have to use application/json for it to work. I believe this is the same for the jQuery and Ext frameworks.


If you are using Ubuntu or Debian and you serve .json files through Apache, you might want to serve the files with the correct content type. I am doing this primarily because I want to use the Firefox extension JSONView

The Apache module mod_mime will help to do this easily. However, with Ubuntu you need to edit the file /etc/mime.types and add the line

application/json json

Then restart Apache:

sudo service apache2 restart

The application/json works great in PHP to store an array or object data.

I use this code to put data in JSON on Google Cloud Storage (GCS) which is set publically viewable:

$context = stream_context_create([
    'gs' => [
        'acl'=>'public-read', 
        'Content-Type' => 'application/json',
    ]
]);

file_put_contents(
    "gs://BUCKETNAME/FILENAME.json", 
    json_encode((object) $array), 
    false, 
    $context
);

To get back the data is straight forward:

$data = json_decode(file_get_contents("gs://BUCKETNAME/FILENAME.json"));

The IANA registration for application/json says

Applications that use this media type: JSON has been used to exchange data between applications written in all of these programming languages: ActionScript, C, C#, Clojure, ColdFusion, Common Lisp, E, Erlang, Go, Java, JavaScript, Lua, Objective CAML, Perl, PHP, Python, Rebol, Ruby, Scala, and Scheme.

You'll notice that IANA.org doesn't list any of these other media types, in fact even application/javascript is now obsolete. So application/json is really the only possible correct answer.

Browser support is another thing.

The most widely supported non-standard media types are text/json or text/javascript. But some big names even use text/plain.

Even more strange is the Content-Type header sent by Flickr, who returns JSON as text/xml. Google uses text/javascript for some of it's ajax apis.

Examples:

curl -I "https://ajax.googleapis.com/ajax/services/search/video?v=1.0&q=jsonexample"

Output: Content-Type: text/javascript

curl -I "https://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&api_key=f82254c1491d894f1204d8408f645a93"

Output: Content-Type: text/xml


Of course, the correct MIME media type for JSON is application/json, but it's necessary to realize what type of data is expected in your application.

For example, I use Ext GWT and the server response must go as text/html but contains JSON data.

Client side, Ext GWT form listener

uploadForm.getForm().addListener(new FormListenerAdapter()
{
    @Override
    public void onActionFailed(Form form, int httpStatus, String responseText) 
    {
        MessageBox.alert("Error");
    }

    @Override
    public void onActionComplete(Form form, int httpStatus, String responseText) 
    {
        MessageBox.alert("Success");
    }
});

In case of using application/json response type, the browser suggests me to save the file.

Server side source code snippet using Spring MVC

return new AbstractUrlBasedView() 
{
    @SuppressWarnings("unchecked")
    @Override
    protected void renderMergedOutputModel(Map model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception 
    {
        response.setContentType("text/html");
        response.getWriter().write(json);
    }
};

JSON (JavaScript Object Notation) and JSONP ("JSON with padding") formats seems to be very similar and therefore it might be very confusing which MIME type they should be using. Even though the formats are similar, there are some subtle differences between them.

So whenever in any doubts, I have a very simple approach (which works perfectly fine in most cases), namely, go and check corresponding RFC document.

JSON RFC 4627 (The application/json Media Type for JavaScript Object Notation (JSON)) is a specifications of JSON format. It says in section 6, that the MIME media type for JSON text is

application/json.

JSONP JSONP ("JSON with padding") is handled different way than JSON, in a browser. JSONP is treated as a regular JavaScript script and therefore it should use application/javascript, the current official MIME type for JavaScript. In many cases, however, text/javascript MIME type will work fine too.

Note that text/javascript has been marked as obsolete by RFC 4329 (Scripting Media Types) document and it is recommended to use application/javascript type instead. However, due to legacy reasons, text/javascript is still widely used and it has cross-browser support (which is not always a case with application/javascript MIME type, especially with older browsers).


As some research,

Most commonly MIME type is

application/json

Let's see a example to differentiate with json and javascript.

  • application/json

It is used when it is not known how this data will be used. When the information is to be just extracted from the server in JSON format, it may be through a link or from any file, in that case, it is used.

For example-

<?php 
  
header('Content-type:application/json');     
   
$directory =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

    
// Showing the json data 

echo json_encode($directory);     


   ?>

Output is,

[{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}]

  • application/javascript

it is used when the use of the data is predefined. It is used by applications in which there are calls by the client-side ajax applications. It is used when the data is of type JSON-P or JSONP. 

For example

<?php 

header('Content-type:application/javascript'); 

$dir =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

echo "Function_call(".json_encode($dir).");"; 

  

?> 

Output is,

Function_call([{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}])

And for other MIME Types see full detail here,

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types


If you are using Ubuntu or Debian and you serve .json files through Apache, you might want to serve the files with the correct content type. I am doing this primarily because I want to use the Firefox extension JSONView

The Apache module mod_mime will help to do this easily. However, with Ubuntu you need to edit the file /etc/mime.types and add the line

application/json json

Then restart Apache:

sudo service apache2 restart

Only when using application/json as the MIME type I have the following (as of November 2011 with the most recent versions of Chrome, Firefox with Firebug):

  • No more warnings from Chrome when the JSON is loaded from the server.
  • Firebug will add a tab to the response showing you the JSON data formatted. If the MIME type is different, it will just show up as 'Response content'.

A part of your question is relevant to me as I just came across it.

A third-party provider is providing a REST service that is used by multiple clients. It's a straight-forward REST called with query parameters that returns a well-formed JSON. I have tested it with PHP and Java where it worked as expected.

My client uses Oracle Service Bus as a gateway between his application server and the Internet. When I made the OSB service, it crashed with an Invalid message format error. Turned out that the content-type being returned was text/html. OSB treats responses as per this header; converting between text, XML and JSON. In this case, the response was JSON but the header didn't say so. Contacting the provider, I got the reply: "We're not going to change it as it doesn't effect anyone else".

The Content-Type header specifies what the content should be, not what it actually is. That is to say, in your consuming program, it's up to you to check or ignore it and process the content in any manner. Another example, you can return GIF data but specify the content type as JSON, then go ahead and ignore the header and read the image data. This won't hurt your program, but may hurt others.

Moral of the story: Play nice.


If you're calling ASP.NET Web Services from the client-side you have to use application/json for it to work. I believe this is the same for the jQuery and Ext frameworks.


The right MIME type is application/json

BUT

I experienced many situations where the browser type or the framework user needed:

text/html

application/javascript

In JSP, you can use this in page directive:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>

The correct MIME media type for JSON is application/json. JSP will use it for sending a response to the client.


In Spring you have a defined type: MediaType.APPLICATION_JSON_VALUE which is equivalent to application/json.


IANA has registered the official MIME Type for JSON as application/json.

When asked about why not text/json, Crockford seems to have said JSON is not really JavaScript nor text and also IANA was more likely to hand out application/* than text/*.

More resources:


Always try to remember these three content types even though there are many content types. as you may have to use these more frequently.

  • Content-Type: application/json
  • Content-Type: application/xml
  • Content-Type: text/html

JSON is a domain-specific language (DSL) and a data format independent of JavaScript, and as such has its own MIME type, application/json. Respect for MIME types is of course client driven, so text/plain may do for transfer of bytes, but then you would be pushing up interpretation to the vendor application domain unnecessarily - application/json. Would you transfer XML via text/plain?

But honestly, your choice of MIME type is advice to the client as to how to interpret the data- text/plain or text/HTML (when it's not HTML) is like type erasure- it's as uninformative as making all your objects of type Object in a typed language.

No browser runtime I know of will take a JSON document and automatically make it available to the runtime as a JavaScript accessible object without intervention, but if you are working with a crippled client, that's an entirely different matter. But that's not the whole story- RESTful JSON services often don't have JavaScript runtimes, but it doesn't stop them using JSON as a viable data interchange format. If clients are that crippled... then I would consider perhaps HTML injection via an Ajax templating service instead.

Application/JSON!


If you get data from REST API in JSON so you have to use content-type

For JSON data: Content-Type:application/json
For HTML data: Content-Type:text/html,
For XHTML data: Content-Type:application/xhtml+xml,
For XML data: Content-Type:text/xml, application/xml

The Content-Type header should be set to 'application/json' when posting. Server listening for the request should include "Accept=application/json". In Spring MVC you can do it like this:

@RequestMapping(value="location", method = RequestMethod.POST, headers = "Accept=application/json")

Add headers to the response:

HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");

Extending the accepted responses, when you are using JSON in a REST context...

There is a strong argument about using application/x-resource+json and application/x-collection+json when you are representing REST resources and collections.

And if you decide to follow the jsonapi specification, you should use of application/vnd.api+json, as it is documented.

Altough there is not an universal standard, it is clear that the added semantic to the resources being transfered justify a more explicit Content-Type than just application/json.

Following this reasoning, other contexts could justify a more specific Content-Type.


As many others have mentioned, application/json is the correct answer.

But what haven't been explained yet is what the other options you proposed mean.

  • application/x-javascript: Experimental MIME type for JavaScript before application/javascript was made standard.

  • text/javascript: Now obsolete. You should use application/javascript when using javascript.

  • text/x-javascript: Experimental MIME type for the above situation.

  • text/x-json: Experimental MIME type for JSON before application/json got officially registered.

All in all, whenever you have any doubts about content types, you should check this link


Of course, the correct MIME media type for JSON is application/json, but it's necessary to realize what type of data is expected in your application.

For example, I use Ext GWT and the server response must go as text/html but contains JSON data.

Client side, Ext GWT form listener

uploadForm.getForm().addListener(new FormListenerAdapter()
{
    @Override
    public void onActionFailed(Form form, int httpStatus, String responseText) 
    {
        MessageBox.alert("Error");
    }

    @Override
    public void onActionComplete(Form form, int httpStatus, String responseText) 
    {
        MessageBox.alert("Success");
    }
});

In case of using application/json response type, the browser suggests me to save the file.

Server side source code snippet using Spring MVC

return new AbstractUrlBasedView() 
{
    @SuppressWarnings("unchecked")
    @Override
    protected void renderMergedOutputModel(Map model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception 
    {
        response.setContentType("text/html");
        response.getWriter().write(json);
    }
};

application/json” is the correct JSON content type.

def ajaxFindSystems = {
  def result = Systems.list()
  render(contentType:'application/json') {
    results {
      result.each{sys->
        system(id:sys.id, name:sys.name)
      }
    }
    resultset (rows:result.size())
  }
}

To complement the rest of the answers, the MIME type for JSON linked data (JSON-LD) according to W3C is:

application/ld+json

Type name: application

Subtype name: ld+json

Additionally, from the same source:

File extension(s):

.jsonld


The correct answer is:

Content-Type: application/json

application/json” is the correct JSON content type.

def ajaxFindSystems = {
  def result = Systems.list()
  render(contentType:'application/json') {
    results {
      result.each{sys->
        system(id:sys.id, name:sys.name)
      }
    }
    resultset (rows:result.size())
  }
}

The proper current standard is application/json. While the default encoding is UTF-8, it is worth mentioning that it could also be UTF-16 or utf-32. When JSON is written in UTF-16 or UTF-32, binary content-transfer-encoding must be used.

There is more information about json here: https://tools.ietf.org/html/rfc4627

more information on binary transfer encoding here: https://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html


In JSP, you can use this in page directive:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>

The correct MIME media type for JSON is application/json. JSP will use it for sending a response to the client.


The proper current standard is application/json. While the default encoding is UTF-8, it is worth mentioning that it could also be UTF-16 or utf-32. When JSON is written in UTF-16 or UTF-32, binary content-transfer-encoding must be used.

There is more information about json here: https://tools.ietf.org/html/rfc4627

more information on binary transfer encoding here: https://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html


The IANA registration for application/json says

Applications that use this media type: JSON has been used to exchange data between applications written in all of these programming languages: ActionScript, C, C#, Clojure, ColdFusion, Common Lisp, E, Erlang, Go, Java, JavaScript, Lua, Objective CAML, Perl, PHP, Python, Rebol, Ruby, Scala, and Scheme.

You'll notice that IANA.org doesn't list any of these other media types, in fact even application/javascript is now obsolete. So application/json is really the only possible correct answer.

Browser support is another thing.

The most widely supported non-standard media types are text/json or text/javascript. But some big names even use text/plain.

Even more strange is the Content-Type header sent by Flickr, who returns JSON as text/xml. Google uses text/javascript for some of it's ajax apis.

Examples:

curl -I "https://ajax.googleapis.com/ajax/services/search/video?v=1.0&q=jsonexample"

Output: Content-Type: text/javascript

curl -I "https://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&api_key=f82254c1491d894f1204d8408f645a93"

Output: Content-Type: text/xml


If you're calling ASP.NET Web Services from the client-side you have to use application/json for it to work. I believe this is the same for the jQuery and Ext frameworks.


I use the below

contentType: 'application/json',
data: JSON.stringify(SendData),

If you're in a client-side environment, investigating about the cross-browser support is mandatory for a well supported web application.

The right HTTP Content-Type would be application/json, as others already highlighted too, but some clients do not handle it very well, that's why jQuery recommends the default text/html.


In Spring you have a defined type: MediaType.APPLICATION_JSON_VALUE which is equivalent to application/json.


The right MIME type is application/json

BUT

I experienced many situations where the browser type or the framework user needed:

text/html

application/javascript

If you're in a client-side environment, investigating about the cross-browser support is mandatory for a well supported web application.

The right HTTP Content-Type would be application/json, as others already highlighted too, but some clients do not handle it very well, that's why jQuery recommends the default text/html.


Not everything works for content type application/json.

If you are using Ext JS form submit to upload file, be aware that the server response is parsed by the browser to create the document for the <iframe>.

If the server is using JSON to send the return object, then the Content-Type header must be set to text/html in order to tell the browser to insert the text unchanged into the document body.

See the Ext JS 3.4.0 API documentation.


JSON is a domain-specific language (DSL) and a data format independent of JavaScript, and as such has its own MIME type, application/json. Respect for MIME types is of course client driven, so text/plain may do for transfer of bytes, but then you would be pushing up interpretation to the vendor application domain unnecessarily - application/json. Would you transfer XML via text/plain?

But honestly, your choice of MIME type is advice to the client as to how to interpret the data- text/plain or text/HTML (when it's not HTML) is like type erasure- it's as uninformative as making all your objects of type Object in a typed language.

No browser runtime I know of will take a JSON document and automatically make it available to the runtime as a JavaScript accessible object without intervention, but if you are working with a crippled client, that's an entirely different matter. But that's not the whole story- RESTful JSON services often don't have JavaScript runtimes, but it doesn't stop them using JSON as a viable data interchange format. If clients are that crippled... then I would consider perhaps HTML injection via an Ajax templating service instead.

Application/JSON!


For specifying the interesting JSON result, you add "application/json" in your request header like below:

"Accept:application/json" is a desired response format.

"Content-Type:application/json" specifies the content format of your request, but sometimes you specify both application/json and application/xml, but the quality of these might be different. Which server will send back the different response formats, look at the example:

Accept:application/json;q=0.4,application/xml;q=8

This will return XML, because XML has higher quality.


To complement the rest of the answers, the MIME type for JSON linked data (JSON-LD) according to W3C is:

application/ld+json

Type name: application

Subtype name: ld+json

Additionally, from the same source:

File extension(s):

.jsonld


For JSON:

Content-Type: application/json

For JSON-P:

Content-Type: application/javascript

I use the below

contentType: 'application/json',
data: JSON.stringify(SendData),

For JSON:

Content-Type: application/json

For JSON-P:

Content-Type: application/javascript

The right content type for JSON is application/json UNLESS you're using JSONP, also known as JSON with Padding, which is actually JavaScript and so the right content type would be application/javascript.


For specifying the interesting JSON result, you add "application/json" in your request header like below:

"Accept:application/json" is a desired response format.

"Content-Type:application/json" specifies the content format of your request, but sometimes you specify both application/json and application/xml, but the quality of these might be different. Which server will send back the different response formats, look at the example:

Accept:application/json;q=0.4,application/xml;q=8

This will return XML, because XML has higher quality.


PHP developers use this:

<?php
    header("Content-type: application/json");

    // Do something here...
?>

Always try to remember these three content types even though there are many content types. as you may have to use these more frequently.

  • Content-Type: application/json
  • Content-Type: application/xml
  • Content-Type: text/html

There is no doubt that application/json is the best MIME type for a JSON response.

But I had some experience where I had to use application/x-javascript because of some compression issues. My hosting environment is shared hosting with GoDaddy. They do not allow me to change server configurations. I had added the following code to my web.config file for compressing responses.

<httpCompression>
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
    <dynamicTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
    </dynamicTypes>
    <staticTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
    </staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>

By using this, the .aspx pages was compressed with g-zip but JSON responses were not. I added

<add mimeType="application/json" enabled="true"/>

in the static and dynamic types sections. But this does not compress JSON responses at all.

After that I removed this newly added type and added

<add mimeType="application/x-javascript" enabled="true"/>

in both the static and dynamic types sections, and changed the response type in

.ashx (asynchronous handler) to

application/x-javascript

And now I found that my JSON responses were compressed with g-zip. So I personally recommend to use

application/x-javascript

only if you want to compress your JSON responses on a shared hosting environment. Because in shared hosting, they do not allow you to change IIS configurations.


JSON (JavaScript Object Notation) and JSONP ("JSON with padding") formats seems to be very similar and therefore it might be very confusing which MIME type they should be using. Even though the formats are similar, there are some subtle differences between them.

So whenever in any doubts, I have a very simple approach (which works perfectly fine in most cases), namely, go and check corresponding RFC document.

JSON RFC 4627 (The application/json Media Type for JavaScript Object Notation (JSON)) is a specifications of JSON format. It says in section 6, that the MIME media type for JSON text is

application/json.

JSONP JSONP ("JSON with padding") is handled different way than JSON, in a browser. JSONP is treated as a regular JavaScript script and therefore it should use application/javascript, the current official MIME type for JavaScript. In many cases, however, text/javascript MIME type will work fine too.

Note that text/javascript has been marked as obsolete by RFC 4329 (Scripting Media Types) document and it is recommended to use application/javascript type instead. However, due to legacy reasons, text/javascript is still widely used and it has cross-browser support (which is not always a case with application/javascript MIME type, especially with older browsers).


The application/json works great in PHP to store an array or object data.

I use this code to put data in JSON on Google Cloud Storage (GCS) which is set publically viewable:

$context = stream_context_create([
    'gs' => [
        'acl'=>'public-read', 
        'Content-Type' => 'application/json',
    ]
]);

file_put_contents(
    "gs://BUCKETNAME/FILENAME.json", 
    json_encode((object) $array), 
    false, 
    $context
);

To get back the data is straight forward:

$data = json_decode(file_get_contents("gs://BUCKETNAME/FILENAME.json"));

Content-Type: application/json - json
Content-Type: application/javascript - json-P
Content-Type: application/x-javascript - javascript
Content-Type: text/javascript - javascript BUT obsolete, older IE versions used to use as html attribute.
Content-Type: text/x-javascript - JavaScript Media Types BUT obsolete
Content-Type: text/x-json - json before application/json got officially registered.


PHP developers use this:

<?php
    header("Content-type: application/json");

    // Do something here...
?>

There is no doubt that application/json is the best MIME type for a JSON response.

But I had some experience where I had to use application/x-javascript because of some compression issues. My hosting environment is shared hosting with GoDaddy. They do not allow me to change server configurations. I had added the following code to my web.config file for compressing responses.

<httpCompression>
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
    <dynamicTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
    </dynamicTypes>
    <staticTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
    </staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>

By using this, the .aspx pages was compressed with g-zip but JSON responses were not. I added

<add mimeType="application/json" enabled="true"/>

in the static and dynamic types sections. But this does not compress JSON responses at all.

After that I removed this newly added type and added

<add mimeType="application/x-javascript" enabled="true"/>

in both the static and dynamic types sections, and changed the response type in

.ashx (asynchronous handler) to

application/x-javascript

And now I found that my JSON responses were compressed with g-zip. So I personally recommend to use

application/x-javascript

only if you want to compress your JSON responses on a shared hosting environment. Because in shared hosting, they do not allow you to change IIS configurations.


JSON:

Response is dynamically generated data, according to the query parameters passed in the URL.

Example:

{ "Name": "Foo", "Id": 1234, "Rank": 7 }

Content-Type: application/json


JSON-P:

JSON with padding. Response is JSON data, with a function call wrapped around it.

Example:

functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});

Content-Type: application/javascript


As some research,

Most commonly MIME type is

application/json

Let's see a example to differentiate with json and javascript.

  • application/json

It is used when it is not known how this data will be used. When the information is to be just extracted from the server in JSON format, it may be through a link or from any file, in that case, it is used.

For example-

<?php 
  
header('Content-type:application/json');     
   
$directory =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

    
// Showing the json data 

echo json_encode($directory);     


   ?>

Output is,

[{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}]

  • application/javascript

it is used when the use of the data is predefined. It is used by applications in which there are calls by the client-side ajax applications. It is used when the data is of type JSON-P or JSONP. 

For example

<?php 

header('Content-type:application/javascript'); 

$dir =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

echo "Function_call(".json_encode($dir).");"; 

  

?> 

Output is,

Function_call([{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}])

And for other MIME Types see full detail here,

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types


Extending the accepted responses, when you are using JSON in a REST context...

There is a strong argument about using application/x-resource+json and application/x-collection+json when you are representing REST resources and collections.

And if you decide to follow the jsonapi specification, you should use of application/vnd.api+json, as it is documented.

Altough there is not an universal standard, it is clear that the added semantic to the resources being transfered justify a more explicit Content-Type than just application/json.

Following this reasoning, other contexts could justify a more specific Content-Type.


Not everything works for content type application/json.

If you are using Ext JS form submit to upload file, be aware that the server response is parsed by the browser to create the document for the <iframe>.

If the server is using JSON to send the return object, then the Content-Type header must be set to text/html in order to tell the browser to insert the text unchanged into the document body.

See the Ext JS 3.4.0 API documentation.


The Content-Type header should be set to 'application/json' when posting. Server listening for the request should include "Accept=application/json". In Spring MVC you can do it like this:

@RequestMapping(value="location", method = RequestMethod.POST, headers = "Accept=application/json")

Add headers to the response:

HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");

If you get data from REST API in JSON so you have to use content-type

For JSON data: Content-Type:application/json
For HTML data: Content-Type:text/html,
For XHTML data: Content-Type:application/xhtml+xml,
For XML data: Content-Type:text/xml, application/xml

As many others have mentioned, application/json is the correct answer.

But what haven't been explained yet is what the other options you proposed mean.

  • application/x-javascript: Experimental MIME type for JavaScript before application/javascript was made standard.

  • text/javascript: Now obsolete. You should use application/javascript when using javascript.

  • text/x-javascript: Experimental MIME type for the above situation.

  • text/x-json: Experimental MIME type for JSON before application/json got officially registered.

All in all, whenever you have any doubts about content types, you should check this link


IANA has registered the official MIME Type for JSON as application/json.

When asked about why not text/json, Crockford seems to have said JSON is not really JavaScript nor text and also IANA was more likely to hand out application/* than text/*.

More resources:


Content-Type: application/json - json
Content-Type: application/javascript - json-P
Content-Type: application/x-javascript - javascript
Content-Type: text/javascript - javascript BUT obsolete, older IE versions used to use as html attribute.
Content-Type: text/x-javascript - JavaScript Media Types BUT obsolete
Content-Type: text/x-json - json before application/json got officially registered.


For JSON, I am using:

 Content-Type: application/json

This is described in the IETF's JSON Data Interchange Format 7158 proposal, Section 1.2: Specifications of JSON.


JSON:

Response is dynamically generated data, according to the query parameters passed in the URL.

Example:

{ "Name": "Foo", "Id": 1234, "Rank": 7 }

Content-Type: application/json


JSON-P:

JSON with padding. Response is JSON data, with a function call wrapped around it.

Example:

functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});

Content-Type: application/javascript


Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to http-headers

Set cookies for cross origin requests Adding a HTTP header to the Angular HttpClient doesn't send the header, why? Passing headers with axios POST request What is HTTP "Host" header? CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Using Axios GET with Authorization Header in React-Native App Axios get access to response header fields Custom header to HttpClient request Send multipart/form-data files with angular using $http Best HTTP Authorization header type for JWT

Examples related to content-type

Passing headers with axios POST request Spring MVC 4: "application/json" Content Type is not being set correctly What are all the possible values for HTTP "Content-Type" header? New lines (\r\n) are not working in email body HTML Input="file" Accept Attribute File Type (CSV) How do you set the Content-Type header for an HttpClient request? Utility of HTTP header "Content-Type: application/force-download" for mobile? Set Content-Type to application/json in jsp file Cannot set content-type to 'application/json' in jQuery.ajax Difference between application/x-javascript and text/javascript content types