Is there any difference between a .json, .txt, .ht

2019-06-24 05:27发布

问题:

The impetus is: I have some JSON that I've been saving as .txt files for a bit. I'd like to rename them all to .json to be more accurate. I'm pretty sure they are both UTF-8, as are most files that can be sent over Ajax.

Anyways, this question raised a bigger question.

Is there any real difference between all of these text types, other than the extension? .html, .json, .css, .js, .txt, .py, etc... they all appear to be the same thing on the inside: a UTF-8 character array.

If you used these interchangeably, would it do anything worse than being confusing? Do any of these have headers? Do any of them encode differently when being saved? Are most .txt files with a different extension?

回答1:

In theory you could use what ever suffix you want.The suffix itself does not have an effect on the content of the file. But applications do different stuff depending on the file suffix. So if you use the wrong or an unknown suffix then you need to tell the application about what file type it is, otherwise it would interpret it wrong.

A webserver would by default add text/html for a file with the suffix htm or html as Content-Type header. And the client then would interpret the received file as html because of that Content-Type. So if you add html to you JavaScript or CSS files then the client might not execute/use them, even if loaded with <link> or <script>.

But if you tell the webserver to send text/css for style.html and application/javascript for script.html then the client might use them correctly. A webbrowser should use the Content-Type header before guessing the type based on the suffix.