JSON for Beginners: Syntax, Rules & Common Mistakes

JSON is the de facto language of data exchange on the web. APIs return it, config files use it, and logs are full of it. It has very few rules, but every one of them produces a cryptic error when broken. This guide explains the syntax skeleton and ends with a lookup table of the most common parse errors.

What JSON Is and Why It Won

JSON (JavaScript Object Notation) appeared in the early 2000s. It is now standardized as RFC 8259 and ECMA-404. It borrows the most portable subset of JavaScript object literal syntax but is deliberately language-independent. Nearly every language ships a parser. Compared with XML, it drops verbose closing tags, so documents shrink, and in a browser a single call to JSON.parse turns text into objects. That combination made it the default format for web APIs.

Six Data Types and the Hard Rules

A legal JSON value is exactly one of six types. Strings are double-quoted. Numbers have no octal or hex forms. Booleans are lowercase true / false, and null is lowercase too. Objects hold key-value pairs in braces, and arrays hold ordered values in brackets. Four rules cause most of the pain:

  • Keys must be double-quoted strings; single quotes or bare keys are invalid.
  • No comments. Both // and /* */ break parsing.
  • No trailing comma after the last member.
  • Strings cannot contain literal line breaks (write \n) or unescaped backslashes (write \\).

One subtle trap: JavaScript handles numbers as 64-bit floats, so integers beyond 2^53 silently lose precision. Order numbers and snowflake IDs often hit this. Well-designed APIs transmit such IDs as strings.

Reading Nested Structures

Real data nests: objects inside arrays inside objects. A user list might be reached at data.items[0].name. That path takes the items array from data, then the name field of element zero. The fastest way to understand a structure is to expand it with the site's JSON Formatter; indentation makes the hierarchy visible. Distinguish containers by their brackets. Square brackets mean an array, accessed by index. Curly braces mean an object, accessed by key.

The Ten Most Common Parse Errors

Wording varies slightly between parsers. The messages below use Chrome / Node.js style, but the causes and fixes are universal.

Error message (example)Typical causeFix
Unexpected end of JSON inputTruncated JSON, such as a missing brace or quote.Format it and check bracket pairing; verify the response is complete.
Unexpected token }Trailing commaRemove the comma after the last member.
Unexpected token 'Single quotes usedUse double quotes for keys and strings.
Expected property name or '}'Key not quotedQuote every key.
Unexpected token /A // or /* */ comment is presentRemove comments; document them elsewhere.
Bad escaped characterWindows path C:\Users with a single backslashWrite C:\\Users or use forward slashes.
Unexpected token < in JSONThe response is HTML (a 404 or error page), not JSON.Check the endpoint URL and the HTTP status code.
Unexpected token u in JSON at position 0JSON.parse(undefined) from an unset variableCheck for null or undefined before parsing.
Unexpected numberLeading zero, e.g. 012Drop the leading zero.
Unexpected token NNaN or Infinity written into the JSONUse null or a string instead.

JSON vs XML vs CSV

  • Web APIs and config files: JSON first. It is compact, expresses hierarchy naturally, and every ecosystem supports it.
  • Namespaces, mixed content, or legacy systems (SOAP, Office documents): XML remains hard to replace; the site's XML Formatter helps untangle it.
  • Flat tabular data heading for Excel: CSV is simplest, but it has no nesting, no types, and tricky quoting rules. The CSV to JSON Converter bridges the two worlds.

Formatting, Minifying and JSON Schema

Pretty-printing and minifying are two forms of the same data. Format, with indentation and line breaks, when debugging, reviewing or documenting; humans read it faster. Minify to one line for transport and storage; the payload is smaller and parsing is marginally faster. A useful habit: when a field "mysteriously" reads as undefined in production, paste the raw response into a formatter. Most such bugs surface within thirty seconds.

Once the team agrees that "this field is required" and "that field must be a number", adopt JSON Schema. It describes structure and constraints, including types, required fields, enums and ranges, in JSON itself. Validation libraries then reject non-conforming data before it reaches your business logic. It is the standard companion for API contracts and config validation.

Common mistakes and how to fix them

Beyond the syntax errors in the table above, a sneakier class exists. The JSON parses perfectly while your logic quietly goes wrong. Six of them are worth checking for.

  • Serializing objects that contain undefined or functions. The mistake: JSON.stringify silently drops undefined properties and functions, with no error and no warning. An API call goes out missing a field, and you spend an hour hunting for the bug in the wrong place. The fix: validate the object against a schema before sending. Express "no value" explicitly as null instead of relying on undefined.
  • Building JSON by concatenating strings. The mistake: '{"name": "' + name + '"}' breaks the moment the variable holds a quote, newline, or backslash. It doubles as an injection vector. The fix: always generate JSON with JSON.stringify or your language's serializer. Build the object first, then serialize it.
  • Comparing two JSON strings with === to detect changes. The mistake: {"a":1,"b":2} and {"b":2,"a":1} are semantically identical but different as text. Caches and change detection misfire, and whitespace differences trigger false changes too. The fix: parse both sides and deep-compare with key order ignored. If you must compare text, normalize both through a stringify step with sorted keys.
  • Tolerating duplicate keys in an object. The mistake: {"port":8080,"port":9090} does not error. Most parsers silently keep the last one, while other implementations behave differently. The same file can yield different values in different environments, a bug that can hide for months. The fix: add duplicate-key detection to schema validation or CI, and enable the editor's JSON validator that flags repeated keys.
  • Ignoring a UTF-8 BOM at the start of the file. The mistake: Windows Notepad saves with a BOM (U+FEFF) by default. JSON.parse then throws "Unexpected token in JSON at position 0". The character is invisible, so you conclude the JSON is fine and the code is broken. The fix: save as "UTF-8 without BOM"; the encoding is switchable in VS Code's status bar. Also strip a leading \uFEFF before parsing.
  • Passing money amounts as floating-point numbers. The mistake: JSON numbers become 64-bit floats in JavaScript, where 0.1 + 0.2 !== 0.3. Totals, discounts, and splits drift until the discrepancy surfaces during reconciliation. The fix: transmit amounts as integers in the smallest unit (cents) or as strings carrying exact decimals, and format them only at the display layer.

Tools mentioned in this guide