Which JSON content type do I use?
Asked Answered
U

39

11548

There are many "standards" for the JSON content type:

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

Which one do I use, and where? I assume security and browser support issues are a factor.

Related: What MIME type if JSON is being returned by a REST API?

Unhallowed answered 25/1, 2009 at 15:25 Comment(0)
O
11532

For JSON text:

application/json

The MIME media type for JSON text is application/json. The default encoding is UTF-8. (Source: RFC 4627)

For JSONP (runnable JavaScript) with callback:

application/javascript

Here are some blog posts that were mentioned in the relevant comments:

Omnipresent answered 25/1, 2009 at 15:27 Comment(12)
Complete list of MIME typesSherer
does it really matter what mime type it has? it's text that gets parsed into an object. wouldn't it be more natural to pass it as text/plain if you want it to be openable in browser without force download, and application/octet-stream if you want it to be automatically downloaded(useful if you're generating it on a webpage intended to be saved locally). Is there really that many people that will need to know the mime type so the downloader can view it with a special json viewer? What am I missing that warrants it a special mime type?Neodymium
Using "text/plain" is a bad practice in general. There are, for instance, attacks in the web platform that would allow cross-origin data theft if you fail to send an appropriate MIME type value.Boffin
Internet Explorer sometimes has issues with application/json - blog is offlineIslamize
Imagine I have a document written by somebody which contains plain text. Now that plain text just happens to be valid JSON as well. Would I then be wrong to use text/plain as its mime-type? JSON is a SUB-TYPE of text. So I think both should be allowed. The question is which works better in practice. According to comment by codetoshare IE has problems with application/json. But no browser should have problems with text/plain. If text/plain is unsafe then how can I serve text-files from my web-site?Atheist
@EugenMihailescu The title of that page is "Incomplete list of MIME types"Tearle
Note that RFC4627 was obsoleted by RFC7159, itself replaced by RFC8259. The information provided here still holds.Whiles
@Tearle True, however that page does have a link to the IANA list of "all" types linked in the answer.Amblygonite
Which are now called Media Types by the IANA.Supernatant
The IETF has once gone around in another circle and is no longer recommending application/javascript as of RFC 9239Tolliver
Also interested in the correct file extension but I'm getting the impression it's json not js but I'd just like a standards reference for that... I've found it here: datatracker.ietf.org/doc/html/rfc4627 in RFC4627 specifying json. D. Crockford, json.org July 2006Haggerty
I also wanted a standards defined file extension which I found: datatracker.ietf.org/doc/html/rfc4627 in RFC4627 specifying json. D. Crockford, json.org July 2006. That's repeated in RFC 7159 and RFC 8259. It's listed in Section 11 "IANA Considerations".Haggerty
T
1809

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:

Tribrach answered 7/4, 2010 at 4:32 Comment(5)
A lot of stuff got put into the text/* section in the early days that would probably be put into the application/* section these days.Philender
@Rohmer - You "can" open anything in a text editor, but a binary format like JPEG or a Windows .exe or a .zip will contain non-printable characters which can actually break many text editors or cause undesired behavior. Try running cat file.jpg for example. Whereas any xml or json file is 100% printable. So I think Stijn de Witt's point is a valid one, despite the fact that yes, it's too late to change now.Pileum
@Pileum You can open any binary with a text editor in HEX form. And all the different characters (the 16 of them) are 100% printable. So, by that logic... are all binaries text? Json is not text. Json is (warning: informal loose definition ahead) a text representation of an object (or array of objects)Shenitashenk
There is no meaning to the phrase "a text editor in HEX form". A Hex editor shows each byte as its hexadecimal value, for example, the byte 1111000 as "78". While there may be some text editors which also happen to have a hex editing mode, this is neither common nor useful for anything but the most technical users doing the most technical tasks. Text, by comparison, means ASCII or Unicode, and in text, the byte 1111000 means lower-case x character. Not 78. JSON is text in exactly the same way as HTML (text/html). It contains only readable text characters, with structured meaning in them.Pileum
I tend to agree with Stijn de Witt. JSON is meant to be viewed and edited with a text-editor.Atheist
P
1026

For JSON:

Content-Type: application/json

For JSON-P:

Content-Type: application/javascript
Parkman answered 20/6, 2012 at 3:10 Comment(1)
JSONP is not really JSON though, it's a technique for passing a JavaScript object literalBurse
D
699

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 Java 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);
    }
};
Dionisio answered 7/10, 2009 at 14:35 Comment(1)
server response must go as text/html. This is true for the ExtJS variant as well.Evidently
F
517

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

Fortuity answered 28/3, 2013 at 7:54 Comment(2)
The definition of JSON is wrong. It does not need to be dynamically generated or respect query parameters. You can serve a static JSON file. Also, the most upvoted answer has a link to the RFC.Citify
Also JSONP can be json data assigned to a var.Sag
I
438

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
Infatuation answered 16/11, 2010 at 22:58 Comment(2)
usually a reload is enough (faster than restart). Also, note that you can now do "sudo service apache2 reload".Shrovetide
Ubuntu 12.04 has this by defaultHalstead
M
417

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.

Minim answered 25/1, 2009 at 15:31 Comment(2)
jQuery seems to work with at least 'application/json' and 'text/plain'... I haven't tried all the others though.Borglum
jQuery is capable of working with content-Type: text/plain, content-Type: application/json, content-Type: application/json; charset=UTF-8, contentType: "application/x-www-form-urlencoded; charset=UTF-8"Rumilly
C
332

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.

Cognition answered 12/4, 2012 at 4:0 Comment(0)
P
323

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.

Physical answered 18/4, 2012 at 8:22 Comment(1)
"So I personally recommending to use application/x-javascript" is where this answer becomes misleading. GoDaddy does allow compression of application/json, I leverage it on my shared hosting and I wouldn't suggest using a different content type to enable compression anyway, it's simply wrong. It can be done, but it will still be wrong. Using different content types for browser support is one thing, using different content types for server-side compression is another.Backwoods
P
285

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'.
Peeve answered 30/11, 2011 at 6:42 Comment(0)
R
268

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.

Russellrusset answered 7/9, 2011 at 2:41 Comment(4)
Tools that don't adhere to standards should be avoided whenever possible; use application/json per spec.Brinton
@Brinton while that is true, it's not specific to ExtJs per se. It's a browser limitation (or rather, perhaps, a "security measure").Monocle
Surely it would be better to use text/plain so it doesn't apply any HTML semantics to non-HTML content? Or don't browsers let you extract a frame's content if it's got no DOM?Chrysoberyl
To add further confusion: I'm just debugging a similar case on Samsung Galaxy Beam (Android 2.3) with default browser, and the iframe seems to fire load event for application/javascript, application/x-javascript, text/javascript, text/plain, but NOT firing it for application/json nor text/html. As of today, Android <=2.3 is About 50% of the Android market share.Aspia
C
243

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!

Cyndy answered 14/5, 2012 at 22:19 Comment(0)
F
224

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.

Fivefold answered 27/4, 2012 at 16:27 Comment(0)
T
189

The correct answer is:

Content-Type: application/json
Therine answered 31/12, 2012 at 6:29 Comment(0)
K
183

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

Kirkman answered 2/4, 2013 at 11:10 Comment(3)
When did text/javascript become obsolete? I'm still filling up HTML documents with <script type="text/javascript" ... tags.Unhallowed
It makes no difference for browsers, really. It's just obsolete for RFC standards: rfc-editor.org/rfc/rfc4329.txtKirkman
@Unhallowed you can safely drop type="text/javascript" and just do <script>...</script> at least according to HTML5.Freehanded
E
164

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.

Enough answered 19/1, 2013 at 8:22 Comment(0)
D
127

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())
  }
}
Dysphasia answered 26/2, 2013 at 11:55 Comment(0)
B
126

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

Backwoods answered 12/2, 2014 at 16:12 Comment(0)
T
98

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
Typology answered 3/5, 2013 at 16:0 Comment(1)
Example of such a situation?Arni
B
82

I use the below

contentType: 'application/json',
data: JSON.stringify(SendData),
Beerbohm answered 16/5, 2013 at 12:43 Comment(0)
K
72

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");
Kwan answered 9/8, 2013 at 10:49 Comment(0)
M
65

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"));
Musa answered 1/4, 2015 at 16:13 Comment(0)
A
65
  • 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 Internet Explorer versions used to use it for HTML attributes.
  • Content-Type: text/x-javascript - JavaScript Media Types, but obsolete
  • Content-Type: text/x-json - JSON before application/json got officially registered.
Accelerometer answered 8/8, 2017 at 3:49 Comment(1)
For JSON text: application/json Content-Type: application/jsonEh
G
63

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

Glimmer answered 29/6, 2013 at 8:34 Comment(1)
That's Java EE too :: javax.ws.rs.core.MediaTypeInstigate
S
58

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.

Shreve answered 6/2, 2015 at 12:1 Comment(0)
H
55

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.

Hemitrope answered 21/6, 2013 at 15:22 Comment(1)
The first part of your answer is wrong. "application/jsonp" is not a valid MIME type. The response body of a JSONP is just JavaScript, so one of the MIME-types for JavaScript has to be used.Somerville
F
50

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.

Flodden answered 25/1, 2009 at 15:25 Comment(1)
application/vnd.api+json seems to be specifically for apis using json:api, a very narrow specification with its own expectations and format, I don't understand it to be for any API that returns json. Please correct me if I'm wrongHime
H
49

PHP developers use this:

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

    // Do something here...
?>
Humankind answered 29/3, 2014 at 5:43 Comment(0)
C
49

If you get data from REST API in JSON, 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
Cicerone answered 11/4, 2016 at 9:15 Comment(0)
C
36

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).

Curson answered 15/2, 2016 at 3:20 Comment(0)
G
21

The most common MIME type is application/json. Here is a list of all JSON content types:

  • Content-Type: application/json - JSON
  • Content-Type: text/x-json - JSON before application/json got officially registered.
  • Content-Type: application/javascript - JSON-P
  • Content-Type: application/x-javascript - JavaScript

Obsolete Types:

  • Content-Type: text/javascript - JavaScript but obsolete. Older Internet Explorer versions used to use it for HTML attributes.
  • Content-Type: text/x-javascript - JavaScript Media Types, but obsolete

Additional References:

RFC4627 - The application/json Media Type for JavaScript Object Notation (JSON)

Gerald answered 12/7, 2022 at 17:42 Comment(2)
Out of curiosity - when did application/json officially get registered ? I have a URL endpoint that outputs JSON, but in text format and not sending a Content-Type: application/json header.Wolves
hi @anjanesh! these references should be helpful: datatracker.ietf.org/doc/html/rfc4627 and iana.org/assignments/media-types/application/jsonGerald
E
15

To complement the previous 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

Exile answered 3/1, 2017 at 22:15 Comment(0)
D
15

As you may have to use these more frequently, always try to remember these three content types even though there are many content types:

  • Content-Type: application/json
  • Content-Type: application/xml
  • Content-Type: text/html
Dichromatic answered 8/4, 2019 at 20:37 Comment(1)
Don't forget text/plainWherewithal
F
14

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.

Felisha answered 4/9, 2016 at 10:21 Comment(1)
If I may start an argument here: The accept header in the request does not make the server reply in that format. As you said, it's the desired format. The q qualifier is a wieghtage. The server app can go ahead and reply in whatever format it desires if it doesn't do as the request says. Along the same vein, if the server app only supports xml, specifying json won't do any auto-convert; you'll get an xml response.Finis
D
14

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 in RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON)

More information on binary transfer encoding is on 5. The Content-Transfer-Encoding Header Field (RFC 1341).

Demulcent answered 17/10, 2016 at 21:40 Comment(0)
H
10

As some research,

The most common 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' => 'Stack Overflow'],
        ];

    // Showing the JSON data

    echo json_encode($directory);
?>

The output is,

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

  • 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' => 'Stack Overflow'],
    ];

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

The output is,

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

And for other MIME types, see the full detail in MIME types (IANA media types).

Homelike answered 13/12, 2020 at 7:50 Comment(2)
What is the difference between JSON-P or JSONP?Suggs
Visit to this page,for JSON-P vs JSONP difference stackoverflow.com/questions/2887209/…Homelike
F
8

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.

Finis answered 29/11, 2019 at 5:17 Comment(0)
L
7

It depends on the point of view.

If you are the client sending a request, then application/json is the right choice.

But if you are the server receiving a request, you have to be prepared, that the client may also send the encoding. So application/json and application/json; charset=utf-8 are valid.

The media type is the same in both cases. But the content type differs.

Logging answered 2/3, 2022 at 14:18 Comment(0)
C
0

The standard and widely accepted JSON content type to use is:

application/json

You should use it because:

  • the content type for transmitting JSON data in HTTP requests and responses.
  • It is the official MIME type for JSON data and is supported by all modern browsers and web servers.

Other are obselete:

The other content types user mentioned (application/x-javascript, text/javascript, text/x-javascript, text/x-json) were used in the past when JSON was not as standardized as it is now. However, using them today is not recommended due to potential security and compatibility issues.

Security Concerns:

  • Some older browsers may interpret JavaScript content types (application/x-javascript, text/javascript, text/x-javascript) as executable scripts, potentially leading to security vulnerabilities if an attacker injects malicious code.

  • Serving JSON data with non-standard content types might trigger security mechanisms in certain browsers or web applications.

Browser Support:

  • While modern browsers have largely standardized on application/json, some older browsers might not handle other content types correctly.
  • application/json is supported by all major browsers and has become the de facto standard for JSON data.

Hope it helps.

Chip answered 29/7, 2023 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.