Reject Malformed UTF-8 JSON Imports with TextDecoder
A game manifest imports successfully, but an asset ID changes during loading. The JSON syntax is valid after decoding because a malformed byte inside a quoted string became a replacement character. A later lookup fails far from the import boundary.
For a file format that requires UTF-8, decode the original bytes with TextDecoder and fatal: true before calling JSON.parse(). This recipe handles complete, small JSON files in modern browsers or Node.js 20 or later.
Reproduce Silent Replacement Inside JSON
Run this example:
The bytes describe an object with an id string, except that its string content contains 0xff, which cannot occur in valid UTF-8. Default decoding repairs that content, leaving a string that JSON accepts. Successful parsing therefore does not establish that the input bytes were valid.
The
TextDecoder fatal reference
documents the two error modes: replacement and throwing TypeError. For imported identifiers, rejecting malformed input keeps the failure at the boundary where the original data is available.
Decode the Original Bytes Before Parsing
Save this as utf8-json.mjs:
The helper accepts a Uint8Array from the same JavaScript realm, including a Node.js Buffer. A view’s offset and length are respected. It returns any JSON value, including arrays, strings, numbers, and null; validating a manifest’s fields belongs to the caller. Cross-frame callers can create a local byte view rather than relying on a foreign realm’s constructor identity.
Malformed UTF-8 throws TypeError during decoding. Well-formed UTF-8 containing invalid JSON throws SyntaxError during parsing. Avoid replacing either failure with an empty manifest, which could make a failed import appear to contain no assets.
Under the default BOM policy, an initial UTF-8 byte order mark is consumed. This helper deliberately accepts that optional prefix. It does not trim other text. The Encoding Standard defines this decoding and BOM behavior. If a format forbids a BOM, check the original prefix explicitly before decoding.
Read a Browser File Without an Earlier Text Conversion
Pass the bytes directly from the selected file:
| |
Use the result only after this promise fulfills. The sample checks the outer shape; add the application’s asset ID, path, and uniqueness rules before changing live state. Reading and parsing hold the file in memory, so apply an application-specific file-size limit before arrayBuffer() for large imports.
Strict decoding needs the original bytes. Calling file.text() first and then encoding that string again cannot recover byte errors already replaced during conversion. Likewise, inspecting a decoded string for \uFFFD cannot distinguish repaired input from a valid file that intentionally contains that character.
Treat the End of Input as Part of Validation
The helper uses one complete-buffer decode. Its default stream: false ensures that an incomplete final sequence is reported immediately:
| |
For a chunked source, keep one decoder for that source, use stream: true for intermediate chunks, and finish with decode() to flush pending bytes. Separate decoders per chunk can reject a valid character split across chunk boundaries. Skipping the final flush can miss a truncated tail. The
decode method reference
describes this stream option.
This file importer needs none of that chunk state. Passing the entire byte view in one call gives it a clear completion boundary. If later adapted to streaming, defer imported-state updates until decoding, parsing, and application validation all finish.
Test Bytes That Parsing Alone Cannot Validate
Save this as test-utf8-json.mjs and run node test-utf8-json.mjs:
| |
The cases cover invalid leading and continuation bytes, overlong encoding, an encoded surrogate, a value above Unicode’s range, and an unfinished sequence. The valid replacement character case prevents an overbroad string-content filter from masquerading as byte validation. Strict decoding checks encoding integrity; JSON syntax and application data rules still need their own checks.