JSON and YAML Syntax: Rules, Common Errors and Safe Parsing
JSON and YAML describe the same kind of data: objects (key and value pairs), lists, strings, numbers, booleans and null. JSON is strict and simple, which makes it the default for APIs. YAML is easier for people to write, which is why configuration files (CI pipelines, Docker Compose, Kubernetes, OpenAPI) use it, but its flexibility hides some traps. This page gives the rules of each, the errors you will see when you break them, and how to parse both safely.
Examples use Python 3.12 with PyYAML 6 (pip install pyyaml inside a virtual environment) and Node.js 22 or later. All output shown is real.
JSON rules
JSON is defined by RFC 8259. The whole format fits in a short list:
- An object is
{"key": value, "key2": value}. Keys are always strings in double quotes. - An array is
[value, value]. - A value is a string in double quotes, a number,
true,false,null, an object or an array. The literals are lowercase. - Numbers are decimal: no leading zeros (
07), no hex, noNaNorInfinity. - Inside strings, escape
"as\", a backslash as\\, and newlines as\n. Any Unicode character is allowed, and JSON sent between systems must be UTF-8. - No trailing commas, no comments, no single quotes.
- Keys in an object should be unique. When they are not, parsers disagree about which value wins, so treat duplicates as a bug.
A valid example:
{
"name": "Ada",
"age": 36,
"admin": false,
"manager": null,
"langs": ["en", "fr"],
"address": {"city": "London", "country": "GB"}
}
JSON errors and what they mean
These five strings each break one rule. Parsing them with Python's json module:
import json
bad_inputs = [
'{"name": "Ada", "langs": ["en", "fr"],}', # trailing comma
"{'name': 'Ada'}", # single quotes
'{"name": "Ada" "age": 36}', # missing comma
'{"debug": True}', # Python's True, not JSON's true
'{"note": "first" // comment}', # comments are not JSON
]
for text in bad_inputs:
try:
json.loads(text)
except json.JSONDecodeError as err:
print(f"{err.msg} (line {err.lineno}, column {err.colno})")
Expecting property name enclosed in double quotes (line 1, column 39)
Expecting property name enclosed in double quotes (line 1, column 2)
Expecting ',' delimiter (line 1, column 16)
Expecting value (line 1, column 11)
Expecting ',' delimiter (line 1, column 18)
Python 3.13 and later report the first one more clearly as Illegal trailing comma before end of object. The same inputs in JavaScript with JSON.parse (Node.js 24):
Expected double-quoted property name in JSON at position 38 (line 1 column 39)
Expected property name or '}' in JSON at position 1 (line 1 column 2)
Expected ',' or '}' after property value in JSON at position 15 (line 1 column 16)
Unexpected token 'T', "{"debug": True}" is not valid JSON
Expected ',' or '}' after property value in JSON at position 17 (line 1 column 18)
The position points at the character where the parser gave up, which is usually just after the real mistake. "Expecting property name" almost always means a trailing comma or single quotes; "Expecting ',' delimiter" means a missing comma on the line above; "Expecting value" or "Unexpected token" means something that is not a JSON value, such as True, None, undefined or an unquoted word. To find the spot quickly, paste the text into the JSON Formatter, which validates and pretty-prints it in your browser.
Parsing and writing JSON safely
Parse JSON with json.loads in Python or JSON.parse in JavaScript. Never use eval: it runs whatever code the text contains. Parsing only proves the text is valid JSON, not that it has the fields you expect, so check the shape before using it:
import json
text = '{"name": "Zoë", "tags": ["admin"], "active": true, "manager": null}'
user = json.loads(text) # JSON text -> Python dict
print(user["name"], user["active"], user["manager"])
# Validate the shape before trusting it
if not isinstance(user.get("tags"), list):
raise ValueError("tags must be a list")
print(json.dumps(user, indent=2, ensure_ascii=False))
Zoë True None
{
"name": "Zoë",
"tags": [
"admin"
],
"active": true,
"manager": null
}
ensure_ascii=False writes "Zoë" as-is instead of ë; both are valid JSON. In JavaScript, watch large integers: numbers are 64-bit floats, so anything above Number.MAX_SAFE_INTEGER (9007199254740991) silently changes:
const user = JSON.parse('{"name": "Zoë", "tags": ["admin"], "id": 9007199254740993}');
console.log(user.name, Array.isArray(user.tags));
console.log(user.id); // larger than Number.MAX_SAFE_INTEGER: precision lost
console.log(JSON.stringify(user, null, 2));
Zoë true
9007199254740992
{
"name": "Zoë",
"tags": [
"admin"
],
"id": 9007199254740992
}
APIs that use 64-bit IDs often send them as strings for this reason. Keep them as strings.
YAML rules
YAML 1.2 is a superset of JSON, so any JSON document is also valid YAML. Most YAML files use the indentation style instead:
- Indentation shows nesting, and it must be spaces. The YAML 1.2 specification forbids tabs for indentation. Two spaces per level is the common convention; what matters is that siblings line up exactly.
key: valueneeds a space after the colon.- A list item starts with
-(dash and space). #starts a comment.- Strings usually need no quotes, but quote anything that could be read as another type (see the next section), and anything containing
:or starting with a special character such as@,*,&,!,{or[. |starts a multi-line string that keeps line breaks;>folds lines into spaces.
# Service settings (YAML allows comments)
name: billing-api
version: "3.10" # quoted: unquoted 3.10 would be the number 3.1
port: 8080
debug: false
country: "NO" # quoted: YAML 1.1 parsers read NO as false
servers:
- host: app1.example.com
weight: 2
- host: app2.example.com
weight: 1
motd: |
Line one keeps its line break.
Line two too.
Loading it and printing it back as JSON shows exactly how a parser read each value:
import json
import yaml # pip install pyyaml
with open("config.yaml", encoding="utf-8") as f:
config = yaml.safe_load(f) # never yaml.load() on untrusted input
print(config["version"], config["country"], config["servers"][1]["host"])
print(json.dumps(config, indent=2))
3.10 NO app2.example.com
{
"name": "billing-api",
"version": "3.10",
"port": 8080,
"debug": false,
"country": "NO",
"servers": [
{
"host": "app1.example.com",
"weight": 2
},
{
"host": "app2.example.com",
"weight": 1
}
],
"motd": "Line one keeps its line break.\nLine two too.\n"
}
YAML values that are not what they look like
Unquoted YAML values are typed by their appearance, and older rules made that surprising. PyYAML implements YAML 1.1, where many more words and number styles are special:
import yaml
for doc in ["version: 3.10", "country: NO", "enabled: yes",
"mode: 0755", "zip: 01234", "time: 12:30"]:
print(f"{doc!r:18} -> {yaml.safe_load(doc)}")
'version: 3.10' -> {'version': 3.1}
'country: NO' -> {'country': False}
'enabled: yes' -> {'enabled': True}
'mode: 0755' -> {'mode': 493}
'zip: 01234' -> {'zip': 668}
'time: 12:30' -> {'time': 750}
A version number became a float that lost its zero, a country code became False, file permissions and a ZIP code became octal numbers, and a time became the number of minutes (base 60). YAML 1.2's core schema fixes most of this (only true and false in their usual capitalizations are booleans, and octal needs 0o), but 3.10 is still a float, and you rarely control which version a tool's parser follows. The reliable fix is to quote any string that looks like a number, a boolean or a time.
YAML errors
A tab in the indentation:
while scanning for the next token
found character '\t' that cannot start any token
in "<unicode string>", line 2, column 1:
host: example.com
^
Misaligned items give expected <block end>, but found '<block sequence start>' or mapping values are not allowed here; the second usually also means a missing space after a colon or an unquoted value containing : . The line and column point at where the structure stopped making sense. In VS Code, the status bar shows whether a file indents with spaces or tabs; click it to convert the file to spaces.
Load YAML safely
Use yaml.safe_load in Python. It builds only plain data: dicts, lists, strings, numbers, booleans, dates and None. yaml.load with the full or unsafe loader can construct arbitrary Python objects from tags in the file, which means a malicious YAML file can run code on your machine. PyYAML 6 makes the risk visible: yaml.load(text) without a Loader argument fails with load() missing 1 required positional argument: 'Loader'. The answer is safe_load, not adding a loader. After loading, validate the values just as you would for JSON.
Which one to use
- JSON for data exchanged between programs: APIs, messages, stored documents. It is strict, so two parsers always agree. Calling a REST API shows it in use.
- YAML for configuration people edit by hand, where comments and multi-line strings help. Quote ambiguous values, indent with spaces, and validate after loading.