Writing JSON Files: How to Produce Valid, Readable JSON

How to write a valid JSON file: the syntax rules, common parse errors, safe serialization from code, what formatting changes, and how to validate before sharing.

What makes a JSON file valid

A JSON file is plain text that follows the grammar defined in RFC 8259 and ECMA-404. A file is valid when a conforming parser can read it without errors. It is usable when the program that consumes it also accepts its structure and values. Those are separate checks, and most problems with JSON files come from confusing them.

  • The top-level value can be an object, array, string, number, true, false or null. Most configuration and data files use an object or an array.
  • Object keys must be strings in double quotes. Single quotes are not allowed for keys or values.
  • Items in objects and arrays are separated by commas, and a trailing comma after the last item is not allowed.
  • Comments are not part of JSON. Neither // nor /* */ is accepted by a strict parser.
  • Numbers are decimal. Leading zeros, hexadecimal, NaN and Infinity are not allowed.
  • Inside strings, the double quote, the backslash and control characters such as a raw newline must be escaped.
  • Whitespace between tokens is limited to space, tab, line feed and carriage return.
  • The specification requires UTF-8 for JSON exchanged between systems that are not part of a closed ecosystem.

A minimal valid example

{
  "name": "Ada",
  "active": true,
  "score": 42.5,
  "tags": ["math", "computing"],
  "manager": null
}

Every key is a double-quoted string. The booleans and null are lowercase and unquoted, and the last item in each container has no trailing comma. The two-space indentation is optional. A parser reads the same data from this file whether it is indented or written on a single line.

Common reasons a JSON file fails to parse

  • A trailing comma after the last array item or object member.
  • Single-quoted strings, or unquoted keys copied from JavaScript object literals.
  • Comments left in a file that a strict parser will read.
  • Curly quotation marks that a word processor, chat app or note-taking tool substituted for straight double quotes.
  • Python-style True, False or None instead of true, false and null.
  • Unescaped backslashes in Windows paths. For example, C:\new has to be written as C:\new.
  • A raw line break inside a string value instead of the \n escape.
  • A non-breaking space or other invisible character outside a string. It looks like a space, but it is not JSON whitespace.
  • A file cut off during copying, so a closing brace or bracket is missing.

Writing JSON from code instead of by hand

Generating a file with a language's JSON serializer avoids most quoting and escaping mistakes, because the serializer applies the rules for you. The examples below write UTF-8, indent with two spaces and end with a newline. JSON does not require a final newline, but many text tools expect one.

import json

data = {"name": "Ada", "tags": ["math", "computing"], "active": True}

with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False, allow_nan=False)
    f.write("\n")
const fs = require("fs");

const data = { name: "Ada", tags: ["math", "computing"], active: true };

fs.writeFileSync("data.json", JSON.stringify(data, null, 2) + "\n", "utf8");

Serializers have defaults worth checking. Python's json module escapes non-ASCII characters unless ensure_ascii is set to False. It also writes NaN and Infinity, which are not valid JSON, unless allow_nan is set to False, in which case it raises an error. JavaScript's JSON.stringify writes NaN and Infinity as null. In objects it silently omits properties whose values are undefined or functions. For configuration files that other processes read, writing to a temporary file and then renaming it into place prevents readers from seeing a half-written file.

What formatting changes, and what it does not

Pretty-printing and minifying only change whitespace between tokens, which the specification treats as insignificant. Spaces inside a string value are data and are kept. The risk comes from tools that parse the file and then write it out again. That round trip can sort keys if sorting is enabled. It can merge duplicate keys, typically keeping only the last value. It can rewrite numbers, so that 1.0 becomes 1 or a very large integer loses precision; JavaScript numbers lose precision beyond 2 to the 53rd power. It can also switch between escaped and literal Unicode. If exact bytes or exact numbers matter, compare the output with the input rather than assuming a formatter left the data alone.

Style | What it changes | Best suited to | Main drawback
Pretty-printed (indented) | Adds whitespace and line breaks between tokens | Files people read, edit or review in version control | Larger file size
Minified | Removes whitespace between tokens | Payloads sent over a network or stored in bulk | Hard to read or compare by eye
ASCII-escaped | Writes non-ASCII characters as \u escapes | Destinations whose encoding handling is uncertain | Text in strings becomes unreadable without decoding
Literal UTF-8 | Keeps characters such as é or emoji as-is | Human-readable files in a UTF-8 workflow | Breaks if a later step assumes a different encoding

In JSON tools, "format" means indentation and layout, not typefaces. Styled "Unicode font" letters, such as the bold or italic mathematical alphanumeric symbols, are different code points from ordinary letters. Putting them in a string value changes the stored data, so exact matching, search and sorting against plain-text values will fail. "Reverse" has no useful meaning for a whole JSON file, because reversing its characters produces invalid JSON. Reversing a string value code point by code point can also separate combining accents from their base letters and break emoji made of several code points.

Unicode and escaping

Any character can be written either literally or as a \u escape of four hexadecimal digits. After parsing, the two forms give the same value. Characters outside the Basic Multilingual Plane, including most emoji, are escaped as a surrogate pair. For example, the grinning face, U+1F600, becomes \ud83d\ude00. In each pair of lines below, both lines decode to the same value.

{"city": "Montréal"}
{"city": "Montr\u00e9al"}

{"mood": "😀"}
{"mood": "\ud83d\ude00"}

Will the file stay readable and usable after copying or sharing?

  • Rich-text destinations can swap straight quotes for curly ones or insert non-breaking spaces. Share JSON as an attached file or inside a code block rather than as formatted prose.
  • The specification says a byte order mark must not be added to JSON sent between systems, and some parsers reject one. Save as UTF-8 without a BOM.
  • Line endings (LF or CRLF) are both valid whitespace and do not affect parsing, though they can produce noisy diffs in version control.
  • Long single-line minified files may be truncated or wrapped by some editors and chat tools. Check that the closing bracket survived the copy.
  • Whether a specific editor, messaging app or upload form preserves the text exactly was not tested for this article. Paste the result back into a validator to confirm it.

Consistent indentation makes nested structure easier to follow visually. How a screen reader announces braces, brackets and quotation marks depends on the product and its punctuation settings, and that was not tested here. When the audience is people rather than programs, a plain-language description or a table of the key values is usually more readable than raw JSON. In that case, provide one alongside the file.

Online formatters and validators were not evaluated for this article, and their data handling cannot be judged from how they look. Do not paste credentials, tokens or personal data into a tool whose retention practices you have not confirmed. Local validation avoids the question entirely.

Validating before you rely on the file

# Python: validates and pretty-prints; exits with an error on invalid JSON
python -m json.tool data.json

# jq: validates without printing output
jq empty data.json

Passing a syntax check only proves the file is well-formed JSON. It does not prove the keys are spelled correctly, the required fields are present or the values have the right types. To check those, validate against a JSON Schema or against the consuming application's own documentation.

Recommendation

For most files that people will open, edit or review:
• Generate them with a serializer rather than typing them by hand.
• Pretty-print with two-space indentation.
• Save as UTF-8 without a byte order mark.
• Validate them before use.
Minify only where size matters, such as network payloads; compression often reduces the difference anyway. Avoid tools that reorder keys or rewrite numbers when exact values matter.
Plain JSON is a poor fit in two cases. If you need comments, use a format the consuming program explicitly supports, such as JSONC, YAML or TOML. Do not leave comments in a file read by a strict JSON parser. If the content is meant for human readers rather than software, prose or a table will serve them better than JSON.

Limits of this review

This article relies on the JSON specification and the documented behavior of common standard libraries. It does not include measurements, file-size comparisons or tests of particular editors, sharing platforms, online tools or assistive technologies. Check behavior in the specific destination you plan to use.