JSON is defined over characters, so how those characters become bytes is a separate question. RFC 8259 settles it for JSON exchanged between systems; older JSON and files inside a closed system can differ.
UTF-8
RFC 8259 section 8.1 requires JSON text exchanged between systems that are not part of a closed ecosystem to be encoded in UTF-8. Earlier specifications allowed UTF-16 and UTF-32 as well, and a program working only with its own files may still use them.
Byte order mark
Implementations must not add a byte order mark (U+FEFF) to the beginning of JSON text
sent over a network. A parser may ignore one rather than treat it as an error, so files
that start with the bytes EF BB BF are read by some software and refused by
others.
Telling the encodings apart
JSON has no signature, and the bytes alone give the encoding only because of a rule from
RFC 4627: the first two characters of a JSON text are always ASCII, so the pattern of zero
bytes in the first four shows which encoding is in use. In this table xx is a
non-zero byte:
| First four bytes | Encoding |
|---|---|
00 00 00 xx | UTF-32 big-endian |
00 xx 00 xx | UTF-16 big-endian |
xx 00 00 00 | UTF-32 little-endian |
xx 00 xx 00 | UTF-16 little-endian |
xx xx xx xx | UTF-8 |
The rule depended on the top level being an object or an array, which is what RFC 4627
required. Now that any value may be at the top level, a one-character text such as
1 has no second ASCII character to test, and RFC 8259 no longer describes
this method. A byte order mark, where there is one, settles it:
| Bytes | Encoding |
|---|---|
EF BB BF | UTF-8 |
FE FF | UTF-16 big-endian |
FF FE | UTF-16 little-endian |
00 00 FE FF | UTF-32 big-endian |
FF FE 00 00 | UTF-32 little-endian |
The application/json registration
Section 11 of RFC 8259 registers the media type with IANA:
| Field | Value |
|---|---|
| Type name | application |
| Subtype name | json |
| Required parameters | None |
| Optional parameters | None |
| Encoding considerations | Binary |
| Magic numbers | None |
| File extension | .json |
| Macintosh file type code | TEXT |
| Intended usage | Common |
| Restrictions on usage | None |
| Change controller | IESG |
No charset parameter is defined for this registration. RFC 8259 notes that
adding one has no effect on compliant recipients, so
application/json; charset=utf-8 means the same as
application/json.
JSON with comments
VS Code’s settings, tsconfig.json and files named .jsonc are
usually “JSON with comments”, which allows // and /* */ comments
and a comma after the last item. It is a convention rather than part of any JSON standard,
and a strict parser such as JavaScript’s JSON.parse turns such a file down.