Parse and read a JSON file
How to read and parse a JSON file safely: what parsing and pretty-printing change, where data can be lost, and when the raw file text is the better choice.
Reading a JSON file can mean two different things. You might want to view the file in a readable layout, or you might want to load it into a program as data you can work with. Both are transformations of the original text, and they change different things. This review covers what each one changes, where data can be lost or altered, and when the raw file is the better thing to keep or share.
Is parsing or reformatting suitable for your use?
For most work, parsing a JSON file with a standard library parser is the right choice. The main benefit is that it checks the syntax and turns the text into structures a program can use: objects become maps or dictionaries, arrays become lists, and strings, numbers, booleans and null become native values. Pretty-printing, which only adds indentation and line breaks, is useful when a person needs to read or review the file.
The main tradeoff is that parsing is not a byte-for-byte round trip. After parsing and writing the data back out, the result can differ from the original in whitespace, escape sequences, key order, duplicate keys and number precision. Usually that does not matter. It matters a great deal when the exact bytes matter.
Keep the original file text, and do not reformat or re-serialize it, in these situations:
- The file is covered by a checksum, hash or digital signature, since any byte change breaks verification.
- You need small, reviewable diffs in version control, and reformatting would rewrite every line.
- The file contains very large integers or high-precision decimals that your parser may round.
- The file may contain duplicate keys, and you need to see all of them rather than whichever one the parser keeps.
- The file uses non-standard extensions such as comments or trailing commas, which a strict parser will reject.
What reading a JSON file actually changes
Pretty-printing changes only whitespace between tokens
Under the JSON standard (RFC 8259 and ECMA-404), whitespace between tokens has no meaning. Indenting or minifying a document therefore leaves the data unchanged while changing the bytes. Only four characters count as whitespace: space, horizontal tab, line feed and carriage return. Whitespace inside a string value is part of the value, and formatters do not touch it.
Many formatters work by parsing the document and serializing it again, rather than only adjusting whitespace. A tool described as a formatter can therefore also make the parsing changes listed below. If exact preservation matters, check how a given tool works before using it.
Parsing converts text into native values
Parsing reads the text, checks that it follows the grammar, and builds in-memory values. That step affects how some data is represented:
- Numbers: the standard does not set a precision limit, but many parsers store numbers as IEEE 754 double-precision values. RFC 8259 notes that integers in the range from -(2^53)+1 to 2^53-1 are interoperable. Integers outside that range, such as some database IDs, can be silently rounded in environments like JavaScript.
- Duplicate keys: RFC 8259 says object names should be unique and describes behavior with duplicates as unpredictable. Many parsers keep only the last value without warning.
- Key order: JSON does not treat object member order as meaningful. Python dictionaries keep insertion order. JavaScript objects list integer-like keys first, in numeric order, which can reorder keys compared with the file.
- Escapes: a string written as \u00e9 and one written as é parse to the same value. When the data is written back out, the serializer chooses its own form. Python's json.dumps escapes non-ASCII characters by default unless ensure_ascii=False is passed.
Validation is a separate question from parsing
A successful parse shows only that the file is well-formed JSON. It does not show that the file contains the fields, types or value ranges your application expects. Checking the structure is a separate step, commonly done with JSON Schema or with explicit checks in code.
Examples of loading a JSON file
Python's standard json module reads from an open file object with json.load. Use json.loads for a string you already have in memory. Parse errors raise json.JSONDecodeError, which is a subclass of ValueError.
import json
with open("config.json", encoding="utf-8") as f:
data = json.load(f)
print(data["name"])
In Node.js, read the file as text and pass it to JSON.parse, which throws a SyntaxError when the input is malformed.
const fs = require("fs");
const text = fs.readFileSync("config.json", "utf8");
const data = JSON.parse(text);
console.log(data.name);
To view a file in readable form from the command line without writing code, Python includes a formatter module. It parses the file and prints it indented, so it reports syntax errors and is subject to the same parsing changes described above.
python -m json.tool config.json
Python's json module accepts NaN, Infinity and -Infinity by default, even though standard JSON does not allow them. A file that loads in Python can therefore still be rejected by a stricter parser elsewhere.
Will the result stay readable and usable after copying or sharing?
Copy and paste
Indented JSON stays valid when copied as plain text. The risk comes from tools that change characters along the way. Word processors, some chat and email clients, and rich-text editors may turn straight quotes into curly quotes or insert non-breaking spaces. Curly quotes cannot delimit JSON strings, and a non-breaking space between tokens is not allowed JSON whitespace, so the pasted text will fail to parse. Moving JSON through plain-text editors, code blocks or file attachments avoids this. Which specific applications perform these substitutions was not tested for this review and should be checked for the tools you use.
Encoding and the byte order mark
RFC 8259 requires UTF-8 for JSON exchanged between systems that are not part of a closed ecosystem. It also says implementations must not add a byte order mark (BOM), while parsers may choose to ignore one. Some editors on some platforms add a BOM anyway. Python's json.loads rejects a string that starts with a BOM. Opening the file with the utf-8-sig encoding removes the BOM before parsing:
with open("config.json", encoding="utf-8-sig") as f:
data = json.load(f)
Non-standard extensions
Comments and trailing commas are common in hand-edited configuration files, but standard JSON allows neither. A file that opens fine in an editor that tolerates them can fail in a strict parser. If you share such a file, either remove the extensions or label the format clearly, for example as JSON5 or JSON with comments, so recipients choose a matching parser.
Accessibility, search and editing
Pretty-printing does not change reading order. Tokens appear in the same sequence as in the original, with indentation added. Indented JSON is generally easier to scan, search line by line and edit by hand than a minified single line. Minified JSON suits machine transfer where size matters.
No documentation or test results were available for this review on how specific screen readers announce deeply nested JSON, or on how particular formatter interfaces work with assistive technology. Those questions remain open. If the audience includes screen reader users, test the actual tool and assistive technology together. For readers who need the content rather than the data structure, a short plain-language summary of the important fields may serve better than the raw document.
Sensitive data and online tools
A web-based formatter or validator may send the pasted content to a server. A tool's appearance or marketing language does not show how it handles or retains that data. For files that contain credentials, personal data or internal configuration, standard-library parsers and command-line tools run locally and avoid the question entirely.
Summary of tradeoffs
| Approach | What changes | Good for | Prefer the original file when |
| Pretty-print or minify | Whitespace between tokens; often more if the tool re-serializes | Human review, smaller transfer size | Hashes, signatures or clean diffs matter |
| Parse into native values | Representation of numbers, duplicate keys, key order, escapes on output | Using the data in a program | Large integers, duplicate keys or exact bytes matter |
| Schema validation | Nothing; it only checks structure and types | Confirming the file meets expectations | Not applicable; it is a check, not a transformation |
In practice, load JSON with a standard parser when you need to use the data. Pretty-print it when a person needs to read it. Keep the untouched original whenever exact bytes, very large numbers or possible duplicate keys are involved.