Publishing JSON files: media type, encoding and parsing
The rules a published JSON file has to follow under RFC 8259, how to serve it over HTTP, and how to write, read, format and validate it with Python's json module without producing output that other parsers reject.
Type: IntermediateVersionRFC 8259On this page
Sites publish JSON for many machine readers: data feeds, API responses saved as static files, search indexes for client-side search, and the JSON-LD blocks inside pages. JSON looks forgiving because almost every language can read it, but the specification leaves several decisions to implementations, and files that rely on one parser's leniency break in another. This page sets out what the standard requires of a published file and then shows how to meet those requirements from Python.
| Specification | RFC 8259, The JavaScript Object Notation (JSON) Data Interchange Format, December 2017; Internet Standard STD 90 |
|---|---|
| Same grammar | ECMA-404, The JSON data interchange syntax, 2nd edition, December 2017 |
| Stricter profile | RFC 7493, The I-JSON Message Format, March 2015 |
| Media type | application/json, with no charset parameter |
| Encoding on the web | UTF-8, without a byte order mark |
| File extension | .json |
What RFC 8259 requires of a published file
- UTF-8. JSON exchanged between systems that are not part of a closed ecosystem must be encoded in UTF-8. A file on a public web server is never part of a closed ecosystem.
- No byte order mark. Implementations must not add U+FEFF at the start of JSON sent over a network. Parsers may ignore one, but many reject it.
- Unique names. Names within an object should be unique. The RFC does not say what a parser does with duplicates, and parsers differ: some keep the last value, some the first, some report an error.
- Portable numbers. Numbers are not limited by the grammar, but values beyond IEEE 754 double precision are not interoperable. Integers are exact only in the range from -(253)+1 to (253)-1, that is up to 9,007,199,254,740,991.
- No NaN or Infinity. Numeric values that the grammar cannot represent, such as NaN and Infinity, are not permitted.
- Any value at the top level. A JSON text can be a single string or number, not only an object or array, though I-JSON advises against relying on that.
Serving JSON over HTTP
The media type is application/json. RFC 8259 defines no charset parameter for it and notes that adding one has no effect on compliant recipients, because the encoding is always UTF-8. Many servers add charset=utf-8 anyway, and it does no harm. JSON-LD documents served as files use their own type, application/ld+json.
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=3600
Access-Control-Allow-Origin: *The Access-Control-Allow-Origin line is needed only if scripts on other sites are meant to read the file; without it, browsers block cross-origin reads while servers and crawlers are unaffected. Media types and status codes for the other site files are covered in serving site files: media types, encoding and status codes.
I-JSON: a profile for files others will parse
RFC 7493 turns the soft points of RFC 8259 into rules. An I-JSON message must be UTF-8, must not contain surrogate code points or noncharacters, and must not have duplicate names in any object. It should not contain numbers beyond double precision; integers outside the exact range should be sent as strings. Protocol designers are advised to use an object at the top level so that new members can be added later and ignored by older readers. A file that follows I-JSON parses the same way in every mainstream JSON library, which makes it a sensible target for anything published for unknown readers.
Python: writing JSON
Python's standard json module writes valid JSON by default with one exception: it writes NaN, Infinity and -Infinity for out-of-range floats, which are not JSON. Passing allow_nan=False makes it raise ValueError instead. By default it also escapes every non-ASCII character as \uXXXX, which is valid but unreadable for Korean, Japanese or accented text; ensure_ascii=False writes the characters themselves, and the file must then be opened with an explicit UTF-8 encoding.
import json
data = {
"site": "example.com",
"title": "사이트맵 안내",
"pages": 128,
"updated": "2026-12-03",
}
with open("site.json", "w", encoding="utf-8", newline="\n") as f:
json.dump(data, f, ensure_ascii=False, indent=2, sort_keys=True, allow_nan=False)
f.write("\n")indent=2 makes the file readable and gives line-by-line diffs in version control; omit it, or pass separators=(",", ":"), for the smallest output. sort_keys=True keeps the order stable between runs, so unchanged data produces an unchanged file. Python's encoder never writes a byte order mark.
Python: reading JSON
json.load and json.loads are lenient in two places where RFC 8259 leaves room. They accept NaN and Infinity, and when an object repeats a name they keep the last value without warning. Both can be tightened with hooks, which is worth doing for files received from elsewhere.
import json
MAX_BYTES = 5 * 1024 * 1024 # refuse anything larger than 5 MiB
def reject_constant(name):
raise ValueError(f"not valid JSON: {name}")
def unique_names(pairs):
obj = {}
for key, value in pairs:
if key in obj:
raise ValueError(f"duplicate name: {key!r}")
obj[key] = value
return obj
def load_strict(path):
with open(path, "rb") as f:
raw = f.read(MAX_BYTES + 1)
if len(raw) > MAX_BYTES:
raise ValueError("file too large")
return json.loads(raw, parse_constant=reject_constant, object_pairs_hook=unique_names)The size check follows the module's own documentation, which warns that malicious JSON from untrusted sources can make the decoder use a great deal of CPU and memory and recommends limiting the size of data to be parsed. Passing bytes to json.loads lets the module detect UTF-8, UTF-16 or UTF-32 itself, and it skips a leading byte order mark in bytes input. A str that begins with a byte order mark is rejected with an error suggesting utf-8-sig; opening text files with encoding="utf-8-sig" accepts files with and without one.
Formatting and validating from the command line
The json module doubles as a command-line tool that parses a file and prints it formatted. From Python 3.14 it runs as python -m json; the older form python -m json.tool still works. If the input is not valid JSON, it prints the parser's error with a line and column and exits with a non-zero status, which makes it usable as a check in a build script.
python -m json --indent 2 --no-ensure-ascii site.json
python -m json.tool site.json > /dev/null && echo "site.json is valid"
curl -s https://example.com/site.json | python -m json --sort-keysThe command-line tool uses the module's default, lenient decoder, so it accepts NaN and duplicate names. For a strict check, call a function like load_strict above from the build instead.
Checking a published file
| Check | How | Expected |
|---|---|---|
| Status and type | curl -sI on the file's URL | 200 and Content-Type: application/json |
| No byte order mark | Look at the first three bytes, for example with head -c 3 file.json | od -An -tx1 | Not ef bb bf |
| Parses strictly | A strict loader such as the one above | No error |
| Large integers | Search for integers of 16 or more digits | IDs and counters beyond 253 written as strings |
| Size | Content-Length, or the file size on disk | Small enough for the clients that will read it |
See also
- Serving site files: media types, encoding and status codesWhich Content-Type each machine-readable file should be served with, why UTF-8 matters, and how crawlers react to redirects, client errors and server errors when they request robots.txt.
- JSON-LD basics: @context, @type and @idHow schema.org structured data is written in JSON-LD 1.1: the script element that carries it, the four keywords most pages need, and the choice between nesting a node and referring to it by @id.
- security.txt: publishing a security contactThe security.txt format defined in RFC 9116: where the file must be served, the two required fields Contact and Expires, the optional fields, signing, and the scope of a single file.
- Canonical and alternate linksA canonical link names the preferred URL when the same content is reachable at several addresses; alternate links point to translations and to the same page in other formats, such as JSON or Markdown. Both can be written in the HTML head or sent as HTTP Link headers.
References
- Bray, T. (ed.). RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format. IETF, December 2017. STD 90. rfc-editor.org
- Ecma International. ECMA-404: The JSON data interchange syntax, 2nd edition, December 2017. ecma-international.org
- Bray, T. RFC 7493: The I-JSON Message Format. IETF, March 2015. rfc-editor.org
- Python documentation. json: JSON encoder and decoder. docs.python.org