Read and parse a JSON file
How to read and parse a JSON file in Python, JavaScript and the command line, what parsing preserves or discards, and when to keep the raw text instead.
Reading a JSON file and parsing it are two separate steps. Reading loads the file's characters into memory as text. Parsing turns that text into data your program can use, such as objects, arrays, strings, numbers, booleans and null. Most problems people hit come from the gap between the two steps: an encoding mismatch during reading, or a detail of the original text that parsing does not keep. This guide covers both steps, what changes along the way, and when to keep the raw text instead.
Should you parse the file, or keep it as text?
Parse the file when you need the values inside it, for example to read a setting, loop over records or validate a structure. Parsing gives you reliable access to the data and fails loudly on malformed input, which also makes it a quick validity check.
The main tradeoff is that parsing keeps the data but not the text. Indentation, spacing, number formatting such as trailing zeros, and the choice between escaped and literal characters are lost. If you write the parsed data back out, the output can differ character for character from the original even when it means the same thing.
Keep the file as plain text when exact bytes matter. Examples include content covered by a hash or signature, files tracked in version control where you want minimal diffs, audit copies, and files containing comments or trailing commas, which strict JSON parsers reject.
How to read and parse JSON in Python
Python's standard library json module reads directly from an open file. Open the file with an explicit encoding rather than relying on the platform default.
import json
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
print(data["name"])
Use json.load for a file object and json.loads for a string you already hold in memory. Invalid input raises json.JSONDecodeError, a subclass of ValueError, which reports the line and column of the problem.
import json
try:
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
except json.JSONDecodeError as err:
print(f"Invalid JSON at line {err.lineno}, column {err.colno}: {err.msg}")
If a file was saved with a UTF-8 byte order mark, json.load on text opened as utf-8 raises an error about an unexpected BOM. Opening the file with encoding="utf-8-sig" strips the mark if present and works normally if it is absent.
How to read and parse JSON in JavaScript
In Node.js, read the file as a string and pass it to JSON.parse. Supplying the "utf8" encoding makes readFileSync return a string instead of a buffer.
const fs = require("node:fs");
const text = fs.readFileSync("data.json", "utf8");
const data = JSON.parse(text);
For non-blocking code, use the promise-based file API.
const { readFile } = require("node:fs/promises");
async function loadJson(path) {
const text = await readFile(path, "utf8");
return JSON.parse(text);
}
In a browser, a page cannot read arbitrary files from disk. A user can pick a file through a file input, and the selected File object exposes its contents as text.
input.addEventListener("change", async () => {
const file = input.files[0];
const data = JSON.parse(await file.text());
});
JSON.parse throws a SyntaxError on invalid input. Wrap the call in try and catch wherever the file comes from outside your control.
Validating and formatting JSON from the command line
Two common tools parse a file and print it back pretty-printed, which both confirms the file is valid and makes it easier to read. Each exits with an error and reports the location if the input is malformed.
python -m json.tool data.json
jq . data.json
The pretty-printed output is a re-serialization, not the original file. The data is the same, but spacing and escaping are chosen by the tool, so do not overwrite the source with it if the exact text matters.
What parsing keeps and what it changes
| Aspect | Kept after parsing? | Notes |
| Strings, booleans, null, arrays, objects | Yes | These map directly to native types in Python and JavaScript. |
| Whitespace and indentation | No | Formatting is presentation only; re-serializing applies the writer's own layout. |
| Key order | Usually | Python dicts keep insertion order. JavaScript objects list integer-like keys first in ascending order, then other keys in insertion order. |
| Duplicate keys | No | The JSON standard leaves behavior unpredictable; Python and JavaScript both keep the last value silently. |
| Large integers | Depends on language | Python integers are unbounded. JavaScript numbers lose precision above 9007199254740991 (Number.MAX_SAFE_INTEGER). |
| Number formatting | No | 1.50 becomes 1.5, and decimal fractions become binary floating-point values. Python can keep exact decimals with json.load(f, parse_float=decimal.Decimal). |
| Escape sequences | Decoded | \u00e9 becomes the character é. Python's json.dumps writes non-ASCII characters back as escapes by default unless ensure_ascii=False. |
| Comments and trailing commas | Rejected | Strict JSON allows neither; formats such as JSONC or JSON5 need a different parser. |
Unicode, emoji and look-alike text
JSON can store characters literally or as \u escape sequences. Characters outside the Basic Multilingual Plane, including most emoji, appear as a pair of escapes when escaped. For example, the grinning face emoji U+1F600 is written as \ud83d\ude00. A standard parser combines the pair into a single character, so the parsed string contains one emoji, not two broken halves.
Parsers do not normalize Unicode. An accented letter can be stored as one precomposed code point or as a base letter followed by a combining mark. Both render the same, but they are different strings, so a key lookup or equality check can fail even though the text looks identical. If your data comes from mixed sources, normalize strings after parsing, for example with Python's unicodedata.normalize, before comparing them.
Will the JSON stay valid after copying or sharing?
JSON is plain text, so it survives copying between code editors and terminals as long as the characters are left alone. The risk comes from destinations that edit text automatically.
- Smart quotes: word processors and some messaging or note-taking tools can replace straight double quotes with curly ones, which makes the JSON invalid.
- Encoding: a file saved in an encoding other than UTF-8 can produce garbled characters or errors when read as UTF-8. The JSON standard requires UTF-8 for data exchanged between separate systems.
- Byte order marks: some editors add one when saving; parsers may reject it, as described for Python above.
- Whitespace changes: rich-text destinations may collapse indentation. This does not break validity, but it removes the readability that pretty-printing provided.
- Truncation: long snippets pasted into size-limited fields can be cut off, leaving unclosed brackets.
When sharing JSON with people rather than programs, send it as an attached file or inside a code block where the destination supports one, and run it through a parser after pasting to confirm it still loads. Pretty-printed JSON is easier to scan and edit by hand than single-line output, and the data is identical either way.
Gaps in the available evidence
No tool-specific evidence was supplied for this review, so it relies on the JSON standard and the documented behavior of the Python and JavaScript standard libraries. It does not include tested results for particular messaging apps, editors or online formatters, so claims about how a named destination handles quotes or whitespace should be checked in that destination. How screen readers announce JSON punctuation also depends on the assistive technology and its settings and has not been tested here. Before pasting data into any online JSON tool, review that tool's own documentation on how input is handled and stored rather than assuming it from the interface.