JSON · 11 min read

Why JSON Requires Double Quotes Around Strings and Property Names

Unquoted property names and single-quoted strings look perfectly readable, yet every strict parser rejects them on sight — because the JSON grammar allows exactly one kind of quote, and everything else is a different language.

Abstract illustration of two quote marks framing a shape

Every developer has done it at least once: paste something that looks like this into a JSON parser and watch it fail.

{ name: 'Ada Lovelace', roles: ['admin', 'editor'] }

The text is readable. The structure is obvious. Any human can tell you what data it describes. And yet the parser rejects it instantly, usually with a message as terse as Unexpected token n in JSON at position 2. The instinctive reaction is that the parser is being pedantic. The correct reaction is to understand that the parser is enforcing the one rule that makes JSON work as an interchange format at all: strings and property names must be wrapped in double quotes — the U+0022 quotation mark — and nothing else in the grammar may take their place.

This guide explains the rule precisely, why the designers of JSON pinned a single quote style instead of allowing several, why so many nearby languages create the confusion in the first place, what strict parsers report when the rule is broken, and how to convert relaxed input into strict JSON without corrupting it along the way.

The rule, stated exactly

RFC 8259, the specification that defines JSON, is unambiguous about this. A string begins and ends with the quotation mark character U+0022. An object is a collection of members, and every member is exactly string : value — which means every property name is itself a string, and therefore must be double-quoted too. There is no alternative delimiter token anywhere in the grammar. The apostrophe U+0027 has no special meaning at all; inside a properly double-quoted string it is just an ordinary character, like the letter a.

The only unquoted tokens JSON recognizes are the three literals true, false, and null, plus numbers. Any other bare word — name, id, active — is not a value the grammar can parse. All four of these inputs are invalid:

{ name: "Ada" }          ← bare property name
{ "name": 'Ada' }        ← single-quoted string value
{ 'name': "Ada" }        ← single-quoted property name
{ `name`: "Ada" }        ← backtick-quoted property name

{ name: 'Ada' }
  ^
  SyntaxError: Unexpected token n in JSON at position 2

{ 'name': "Ada" }
        ^
  Expecting property name enclosed in double quotes

Note what the error messages do and do not say. Neither claims the input is nonsense. Both point at the exact character where the grammar stopped matching, which is the character that should have been a quotation mark. If you have ever stared at a position number and wondered how to translate it into a line and column, we have a separate guide on reading JSON syntax errors by line and column that covers the mapping.

Two related points sharpen the rule. First, because property names are strings, even keys that look like numbers must be quoted: {"2": "even"} is valid; {2: "even"} is not. There is no separate identifier production in the grammar, so a key can be any string at all — {"": "surprise"} is valid JSON with a property whose name is the empty string, and keys containing spaces, emoji, or newlines are legal as long as the awkward characters are escaped.

Second, distinguish quoting from escaping. The double quote plays two roles: it delimits the string, and — like the backslash and the control characters — it must be escaped with a backslash when it appears inside the string. The apostrophe plays no role at all, which produces an asymmetry people find backwards at first: inside a JSON string, a double quote needs a backslash and an apostrophe needs nothing.

{ "quote": "She said \"no\" twice" }   ← delimiter escaped: \"
{ "quote": "She said it's fine" }      ← apostrophe literal: no escape

A related failure that has nothing to do with quote style but produces identical symptoms: copy text from a rendered web page or a rich-text editor and the straight quotes silently become curly quotes — U+201C and U+201D — which look nearly identical to U+0022 but are different characters that no JSON parser accepts. That trap deserves its own guide; see JSON copied from HTML.

Why the designers pinned one quote style

Allowing multiple quote styles was technically feasible — several formats do it — so the choice to allow exactly one deserves an explanation. Three reasons dominate.

Determinism

A data interchange format is an agreement between programs that will never meet each other: a service in one language emits bytes, a service in another language consumes them. If two quote styles were legal, the same document would have two valid spellings, and every downstream property that depends on exact bytes starts to wobble. Canonicalization, byte-level comparison, caching, hashing, and signing all assume one canonical form. One quote style makes the canonical form trivial: serialize the same structure twice, in any compliant implementation, and the output matches byte for byte (for a given serializer's whitespace choices).

Simple parsers

With a single delimiter, the scanner for strings is a handful of lines: see ", consume until the next unescaped ", handle backslash escapes. There is no lookahead, no state to decide whether an apostrophe opens a string or merely sits inside one. This simplicity is a feature, not an accident. JSON was explicitly designed so that a compliant parser could be written in an afternoon in any language, including the ones with weak regular-expression and string-handling facilities. Every additional syntax freedom multiplies the parser states, and every additional parser state multiplies the places where independent implementations disagree — which is exactly the failure mode an interchange format exists to prevent.

A concrete thought experiment shows how quickly the states multiply. Give a scanner two quote styles, and it must now decide, on seeing an apostrophe, whether that apostrophe is a delimiter or content — a decision that in general requires scanning context the scanner does not yet have. Add bare keys, and it must classify every unquoted word as either a reserved literal, an identifier-shaped key, or a syntax error. Each decision point is a place where two independently written parsers can make a different call on the same bytes, and once they do, the format stops being a format and becomes a set of dialects with a shared name.

No escaping ambiguity

Once two quote styles are legal, a question arises that has no clean answer: may a string delimited by one style contain the other style without escaping? If yes, the parser must track which of two escape contexts it is in, and the same literal text can encode differently depending on its delimiter — a subtle trap for anyone writing generators or templates. If no, the format gains complexity and saves nothing. By choosing one delimiter, JSON sidesteps the question entirely: a double quote inside a string always means escape it as \", and an apostrophe inside a string never needs escaping at all. One delimiter, one escape rule, no ambiguity.

There is also a historical footnote: JSON was extracted from JavaScript object literal syntax around 2001, and double quotes were the quoting convention shared by the C family of languages — C, C++, Java, C# — that dominated the server side at the time. Pinning that convention maximized familiarity for the audience the format needed to win over. But the three reasons above are the durable ones; the history only explains which style won, not why there was a contest with a single winner.

The determinism argument has a concrete form worth spelling out. Software-signed manifests, content-addressed caches, and deduplicating message queues all key off the serialized bytes of a document. If one producer wrote {id: 1} and another wrote {"id": 1} and both were legal, the same logical object would hash to two different values, land in two cache slots, and satisfy two different signatures. Debugging that means inventing a canonicalization layer — normalizing quotes before hashing — which is precisely the extra machinery the format was designed to make unnecessary. Every relaxation of the surface grammar pushes canonicalization work out of the parser and into every consumer.

Where the confusion comes from

The rule would be easy to remember if JSON lived alone. It does not. Developers work daily in several languages whose literal syntax looks almost identical to JSON but is deliberately more permissive, and the differences are exactly the ones the grammar forbids.

JavaScript object literals

JavaScript is the biggest offender, for the simple reason that JSON is a subset of its literal syntax. A JavaScript object may use bare identifier keys, single-quoted strings, and backtick template literals; none of that is JSON. This is also the source of the most seductive debugging experience: paste relaxed input into a browser console and it evaluates fine — because the console executes JavaScript, it does not parse JSON. JSON.parse and a JS engine evaluating an object literal are two different interpreters running two different grammars. It works in my console proves the input is valid JavaScript, which was never the question.

Python dictionaries

Python's dict literal allows both quote styles (single quotes are the community convention), and its boolean and null literals are capitalized: True, False, None instead of true, false, null. A dict printed to the terminal looks like JSON and is not. The same applies to many other ecosystems in milder forms: YAML allows unquoted keys and scalar values by default; TOML, HCL, and various config languages each relax some subset of the rules. Every one of them is a fine tool for its own job — none of them is JSON.

// JavaScript object literal — valid JS, not JSON
{ id: 7, active: true, tags: ['a', 'b'] }

// Python dict literal — valid Python, not JSON
{'id': 7, 'active': True, 'tags': ['a', 'b']}

// JSON — the only form a strict parser accepts
{"id": 7, "active": true, "tags": ["a", "b"]}

YAML and the shape-shifting config family

YAML relaxes quoting in the opposite direction: most scalars need no quotes at all, comments start with a hash, and structure comes from indentation rather than braces. The same payload that JSON spells with quoted keys and values, YAML spells with none of them:

# YAML — valid YAML, not JSON
id: 7
active: true
endpoint: https://api.example.com/v1   # unquoted scalar, comment allowed
tags:
  - a
  - b

The relationship between the two formats adds one more layer of confusion: YAML 1.2 is a superset of JSON, so every strict JSON document is also valid YAML, but the reverse is false — and plenty of YAML 1.1 parsers in the wild do not even honor the superset claim. The practical consequence is asymmetric trust: you may feed JSON into a YAML tool, but you may never feed relaxed YAML into anything that expects JSON. The same caution applies to TOML, HCL, and the permissive conventions of .env files and shell configuration, each of which looks JSON-adjacent in places and each of which follows its own grammar.

The table below summarizes the common input styles, whether a strict JSON parser accepts them, and what the fix looks like.

Input styleValid JSON?What a strict parser saysFix
{"id": 7}YesAcceptedNothing to do
{id: 7}NoUnexpected token at the keyWrap the key in double quotes
{'id': 7}NoExpecting property name enclosed in double quotesReplace the apostrophes with double quotes
{`id`: 7}NoUnexpected token at the backtickReplace the backticks with double quotes
{"name": 'Ada'}NoUnexpected token at the string valueReplace the apostrophes with double quotes
{"flag": True}NoUnexpected token TLowercase to true
{"greeting": “hi”}NoUnexpected token (invisible to the eye)Replace curly quotes with straight U+0022

The last row is worth a second look: it fails for a character reason rather than a grammar reason, and it is the failure most likely to survive a code review, because the source and the corrected version look identical in most fonts.

Tooling can carry part of this burden for you. Most editors with JSON language support underline quote violations as you type, and every serious linter reports the same class of errors before anything reaches a parser that matters. The catch is that those helpers only run where they are installed; the file you email to a colleague, the payload you paste into a curl command, and the document a partner system uploads are all validated by nothing but the strict parser on the receiving end. Treat editor checks as a convenience, not a contract — the contract is the grammar, and the grammar is enforced the first time the text meets a real JSON.parse.

What strict parsers report, and why leniency is dangerous

When the quoting rule is broken, parsers fail fast and fail specifically. JavaScript's JSON.parse reports the offending token and its character offset; Python's json module reports the expectation that was violated along with line, column, and character position; Java's Jackson reports the token it found and the token it wanted. Feed the same broken document to each and the family resemblance is easy to see — every message is pointing at the character that should have been, or should not have been, a quotation mark:

Input: {'id': 7}

JSON.parse("{'id': 7}")
  SyntaxError: Unexpected token ' in JSON at position 1
               (V8 wording varies by version; the position is the delimiter)

Python json.loads("{'id': 7}")
  json.decoder.JSONDecodeError: Expecting property name enclosed in
  double quotes: line 1 column 2 (char 1)

Jackson (Java)
  JsonParseException: Unexpected character ('''' (code 39)):
  was expecting double-quote to start field name

These messages look unhelpful until you learn to read them as coordinates rather than explanations — the parser is telling you where the grammar stopped, and the character before that position is almost always the one that needs a pair of double quotes around it, or a pair of double quotes instead of the apostrophes it is wearing.

Given how consistent the errors are, it is tempting to ask why parsers do not simply accept the near-JSON and move on. The answer is that leniency is not convenience — it is a deferred failure with interest. Suppose a parser accepts bare keys and single quotes. Now the ecosystem around it splits: one producer emits bare keys because its parser tolerates them, another tool passes the text through untouched, and the strictest consumer in the chain — often a third-party API you do not control — rejects the payload three hops away from where the mistake was made. The failure moves from the moment of parsing, where it is cheap and precisely located, to a boundary between systems, where it is expensive and diagnosed over a video call.

There is a security dimension too. Lenient parsers must make judgment calls about ambiguous input, and judgment calls about untrusted input are where vulnerabilities live. The history is instructive: early JavaScript ecosystems parsed JSON with eval, which happily accepted relaxed syntax — and equally happily executed anything that was not data at all. Modern parsers gain safety precisely by refusing to interpret anything the grammar does not explicitly define. A parser that says this byte sequence means exactly one thing or nothing is a parser that cannot be talked into a second meaning.

A parser that accepts almost-JSON does not remove the quoting rule. It just moves the rule's enforcement from a precise error at parse time to a vague breakage at integration time. Strictness at the boundary is what keeps the failure local.

JSON5 and other relaxed formats, as opt-in choices

None of this means relaxed syntax is bad — it means it belongs to formats that declare themselves. JSON5 is a well-specified superset of JSON that permits unquoted keys, single-quoted strings, trailing commas, comments, hexadecimal numbers, and more. JSON with comments (often called JSONC) is the variant used by tsconfig.json and VS Code settings. YAML goes much further. These formats exist because humans hand-editing configuration genuinely benefit from comments and relaxed quoting.

The operative word is opt-in. A JSON5 document requires a JSON5 parser at both ends of the conversation, agreed in advance. What is never acceptable is smuggling a dialect through a strict door: writing JSON5 syntax into a file named .json, or sending it to an endpoint documented to speak RFC 8259 JSON, and relying on luck about which parser is on the other side. The same discipline applies to trailing commas and comments — we cover the specifics in the guide on comments and trailing commas in JSON.

// JSON5 — valid only where a JSON5 parser is the agreed contract
{
  // retries before the client gives up
  retries: 5,
  endpoint: 'https://api.example.com/v1',
  headers: { 'x-trace': 'on' },
}

// Strict JSON — the same data, acceptable anywhere
{
  "retries": 5,
  "endpoint": "https://api.example.com/v1",
  "headers": { "x-trace": "on" }
}

Choosing between them is straightforward. Configuration files edited by humans, where both the writer and the reader are known tools, are the natural habitat of JSON5, JSONC, YAML, and TOML. Wire formats between systems, stored documents, API payloads, and anything with an unknown or untrusted consumer must be strict JSON. When in doubt, strict JSON is never the wrong answer; it is the only spelling every JSON parser on Earth accepts.

One practical warning closes this section: dialects spread by accident faster than by decision. A developer pastes relaxed syntax into a file because their editor's lenient plugin validates it, the file gets copied into a project, and months later a build tool with a strict parser fails on a Friday afternoon. If a repository intends to speak JSON5, say so — in the file extension, the README, and ideally a lint rule that rejects strict-only violations in the other direction. A dialect without a declared boundary is just a future parsing error with extra steps.

Converting relaxed text to strict JSON safely

Eventually you will hold a file of almost-JSON — exported from a log, scraped from documentation, pasted from a Python session, or generated by an internal script whose author never quite finished the serializer — and need it in strict form. The conversion has a right way and several popular wrong ways, and the difference between them is usually invisible until the converted file meets a strict parser downstream.

The wrong way: blind regex

The two transformations people reach for first are quote the bare keys and swap single quotes for double quotes. Quoting keys is mostly safe with a careful pattern anchored to structural positions. Swapping quote characters is not, because apostrophes occur legitimately inside string content, and a blind replacement cannot tell a delimiter from an apostrophe:

// Input — one delimiter and one apostrophe, visually similar
{ 'note': 'it's not ready yet' }

// Naive single-quote swap — corrupts the document
{ "note": "it"s not ready yet" }   ← two broken strings now

// Correct result — the apostrophe needs no escape inside double quotes
{ "note": "it's not ready yet" }

The naive swap did not just fail to fix the input; it turned one broken document into a differently broken one, and the corruption sits in the middle of a string where position-based error reporting becomes misleading. Strings containing contractions — it's, doesn't, user's — are common in real data, which makes this trap a certainty rather than a corner case.

The right way: parse leniently, serialize strictly

The robust approach avoids text surgery altogether. Parse the relaxed text with a parser that accepts the dialect it is actually written in, then re-serialize the resulting structure with a strict serializer. Parsing understands the difference between a delimiter and an apostrophe; regular expressions do not.

# Python: convert relaxed JSON5 input to strict JSON
import json, json5     # pip install json5

with open("relaxed.json5") as f:
    data = json5.load(f)            # lenient parse; understands ' and bare keys

strict = json.dumps(data, indent=2) # strict dump; every quote is U+0022
print(strict)

The same pattern exists in every ecosystem — JSON5 parsers for JavaScript, Java, Go — and it comes with a bonus: the round trip through a real parser also normalizes the literal soup (True to true, None to null in Python-sourced text) and strips comments and trailing commas as a side effect, since those constructs evaporate during parsing and never reappear in strict output. A worked example makes the payoff concrete:

# From a Python session — valid Python, not JSON
{'cache': None, 'verbose': True, 'note': "don't ship yet"}

# After a lenient parse and strict re-serialize — valid JSON
{
  "cache": null,
  "verbose": true,
  "note": "don't ship yet"
}

Notice the source line itself: the Python author wrapped the note in double quotes because the text contains an apostrophe — a completely idiomatic Python choice, and exactly the habit that leaves files with a mixture of quote styles that defeats any single find-and-replace. Only a parser can untangle that mixture, because only a parser knows which quote is a delimiter and which is content.

One caution if you do choose regex for the key-quoting step anyway: keys may contain characters that themselves need escaping once quoted. A bare key like user-name quotes trivially, but text scraped from the wild can yield keys containing double quotes or backslashes, and quoting them without escaping their contents produces a document that fails at the next validation step. Yet another reason the parse-and-reserialize path wins: it handles the escaping for you.

A debugging checklist for quote-shaped failures

When a parser rejects input that looks obviously fine, run down this list in order. In practice the first three items resolve the large majority of cases.

  1. Inspect the quote characters themselves. A straight apostrophe and a curly quote, or a straight double quote and a typographic one, are different code points. Copy-paste from web pages and rich editors is the usual culprit; see the guide on JSON copied from HTML.
  2. Check every property name for quotes. Bare keys are valid in JavaScript, YAML, and JSON5 — and invalid in JSON. Every key, including numeric-looking ones, needs double quotes.
  3. Replace single-quoted strings carefully. Swap the delimiters to double quotes, but handle apostrophes inside the content first — or better, run a lenient parse and strict re-serialize as described above.
  4. Hunt for backticks. They never belong in JSON. They usually arrive from template literals or from markdown-adjacent tooling.
  5. Normalize the literals. Python's True, False, None become true, false, null. This fails for quote reasons adjacent to the quoting problem and is easy to miss in a wall of text.
  6. Remove trailing commas and comments if the source came from a JSONC or JSON5 context — both are banned in strict JSON, and both produce error positions unrelated to where the excess character sits.
  7. Re-validate in a strict parser before shipping. Passing strict validation is the only proof that matters; eyeballing the quotes is not.

For a deeper treatment of step seven — turning the position numbers in parser errors into actual lines and columns in your editor — the guide on JSON syntax errors by line and column walks through the arithmetic for the major parsers.

Test it yourself

Paste each rejected sample from this guide into the JSON Inspector and watch where the parser stops: the bare key fails at the first letter, the single-quoted value fails at the apostrophe, and the curly-quoted string fails at a character you cannot see. Apply the fix, re-validate, and confirm the document parses. Every example runs entirely in your browser, so you can experiment freely with malformed input without any of it leaving your machine.

Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.