Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Kubernetes: error converting YAML to JSON: did not find expected key

kubectl rejects a manifest before the API sees it. Find the exact line, fix indentation, quoting, and tabs, and validate locally before applying.

~5 min readKubernetes
#kubernetes#yaml#kubectl#manifests
Bold white headline reading YAML BROKEN with a Kubernetes manifest scroll misaligned at a cyan parser gate.

Introduction & Quick Summary

kubectl refuses a manifest before it ever reaches the API server:

error: error converting YAML to JSON: yaml: line 12: did not find expected key

The message is produced by the YAML parser inside kubectl, not by Kubernetes. Kubectl reads the file, converts YAML to JSON, and validates the object locally; a syntax error stops the request at the first step. The line number points near the problem, usually at or just after the line whose indentation broke the document's structure.

Where it appears:

  • kubectl apply -f deployment.yaml with hand-edited indentation.
  • A --- separated multi-document file where one document is malformed.
  • Rendered Helm output piped into kubectl, where the template produced an empty or misindented block.
  • A ConfigMap built from an external file, with a bad indent under data:.
  • CI pipelines that generate YAML from templates or string concatenation.

Quick answer: open the reported line, look at the line above it, and fix the indentation, the tab character, or the unquoted value that contains a colon. Then validate locally with --dry-run=client before applying.

Core Mechanics, Signatures & Reproducible Setup

Kubectl uses a YAML library that reports parser-level failures with line N: <reason>. The line is the position where the parser gave up, which is often one line after the real mistake. Kubernetes object structure is strict: mappings are indented consistently, list items are introduced with - , and a value that contains : must be quoted.

# broken.yaml -- reproduce with: kubectl apply -f broken.yaml --dry-run=client apiVersion: apps/v1 kind: Deployment metadata: name: web spec: replicas: 2 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: web image: nginx:1.27 ports: - containerPort: 80
error: error converting YAML to JSON: yaml: line 12: did not find expected key

Line 12 is ports:, indented one space deeper than image: without starting a new list item or mapping key. The parser expected either a sibling key at the same level or a new - item.

The parser messages form a small family, and each points at a different repair:

MessageUsual causeRepair
did not find expected keybad indentation, tab characteralign the key with its siblings
did not find expected '-' indicatorlist item missing - add the dash at the right indent
found character that cannot start any tokentab used for indentationreplace tabs with spaces
mapping values are not allowed in this context: inside an unquoted scalarquote the value
could not find expected ':'list item written as a mappingadd the key and colon
did not find expected node contentempty value after a key, or stray ---give a value or remove the line

A minimal, valid version of the same object, useful as a reference while repairing:

apiVersion: apps/v1 kind: Deployment metadata: name: web spec: replicas: 2 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: web image: nginx:1.27 ports: - containerPort: 80

Both list styles are legal: - aligned with the parent key, or indented under it. What is not legal is mixing the two inside one list.

Key Comparison Table

CheckCommandWhat it catches
Client-side validationkubectl apply -f x.yaml --dry-run=clientYAML syntax and unknown fields
Server-side validationkubectl apply -f x.yaml --dry-run=serveradmission and schema errors
Render without applyingkubectl create -f x.yaml --dry-run=client -o yamlconfirms parsed output
Schema validation offlinekubeconform -strict x.yamlwrong apiVersion and field types
Generic YAML lintyamllint -d relaxed x.yamlindentation, tabs, trailing spaces
Browser conversionYAML to JSONwhether the document parses at all

Repair strategies, by symptom:

SymptomFastest fixWhy it works
One file, one errorfix the reported line and the line abovethe parser stopped at the first structural break
Large generated fileparse it with a tool to find the first failurekubectl reports only the first error
Error only in CIinspect the generated file, not the templatestring concatenation usually lost a newline
Error only after adding a blockcheck the block's indentation against siblingspasted blocks carry their original indentation

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Read the line above the reported one

The reported line is where the parser noticed the break, not always where it was made.

# the mistake is here, on line 11: a tab before "ports:" image: nginx:1.27 ports:
bash
sed -n '9,14p' broken.yaml | cat -A # ./ image: nginx:1.27$ # ^Iports:$

cat -A prints tabs as ^I, which makes an invisible tab obvious. Replace tabs with spaces; YAML forbids tab characters in indentation.

2. Fix list indentation without rewriting the object

Two legal forms exist, and mixing them is the most common cause of this error in generated files.

# form A: dash at the same indent as the parent key containers: - name: web image: nginx:1.27 # form B: dash indented under the key containers: - name: web image: nginx:1.27 # broken: dash at one indent, keys at another containers: - name: web image: nginx:1.27

When you edit by hand, copy the indentation of the sibling block you already have instead of typing spaces. When you generate YAML, emit one form consistently.

3. Quote values that contain YAML syntax

A colon followed by a space inside an unquoted scalar ends the key. Container arguments, annotations, and environment values hit this constantly.

# broken: the parser sees a mapping value inside a scalar data: config: server=localhost:8080 cache=on # correct data: config: "server=localhost:8080 cache=on" # also correct: block scalar data: config: | server=localhost:8080 cache=on

The block scalar is the safer form for anything multi-line, such as an nginx config or a JSON blob inside a ConfigMap.

4. Validate multi-document files one document at a time

Kubectl stops at the first broken document, so a file with ten objects tells you about one. Splitting it finds the rest quickly.

bash
# split on document separators, then check each part csplit -sz manifests.yaml '/^---$/' '{*}' for f in xx*; do kubectl apply -f "$f" --dry-run=client >/dev/null 2>&1 || echo "broken: $f" done

A --- with trailing characters, such as --- # prod, is a separate common break: the separator must be exactly three dashes at column zero.

5. Check what Helm actually rendered

A template error shows up as this message because the rendered output is broken, not the chart. Render first, inspect, then apply.

bash
helm template my-release ./chart -f values.yaml > rendered.yaml yamllint -d relaxed rendered.yaml || true kubectl apply -f rendered.yaml --dry-run=client

Paste the rendered file into the YAML converter to see the parsed JSON when the error line is inside a generated block; the JSON view makes a misplaced key obvious. Compare a working and a broken render with Diff to find the one changed indent.

Common Compilation/Runtime Mistakes & Version Gotchas

Trusting the line number exactly. In practice the parser reports the line where it failed, which is often one line below the broken indent. Always inspect the reported line together with the two lines above it.

Editing in an editor that inserts tabs. Some editors detect YAML and switch to spaces, others do not. Set expandtab for *.yaml, and add a pre-commit lint so a tab cannot be committed.

Using YAML 1.1 booleans. Before Kubernetes 1.25, some fields documented as strings accepted yes, no, on, and off, which YAML 1.1 reads as booleans. YAML 1.2 parsers read them as strings, and the conversion can change a value's type without any syntax error. Quote every value that can be read as a boolean or a number: "on", "no", "1.0".

Assuming kubectl apply validated the schema. Client-side dry run checks structure, not whether the API accepts the fields. Use --dry-run=server when you need real admission and schema checks, and expect it to require cluster access.

Fighting the error with kubectl replace. The parse error happens before any request, so changing the verb cannot help. Only the file content matters until the document parses.

Version differences. Kubernetes removed several deprecated API versions in 1.22 and 1.25, and a manifest that parses cleanly can still be rejected for an unknown apiVersion; the error then starts with unable to recognize rather than error converting. Kubectl also changed some client-side validation messages across 1.24 to 1.28, so a CI image pinned to an older kubectl may report a different line for the same file.

Practical order of operations. Convert the file with the YAML tool to confirm it parses, fix indentation, then run kubectl apply --dry-run=client, then --dry-run=server, and only then apply. That order keeps every failure cheap and local.

Reference material: Declarative object configuration and Configuration best practices.

Official references

primary documentation

The Kubernetes documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Kubernetes guides

More in Kubernetes

All Kubernetes guides

The guides filed next to this one in Kubernetes, in library order.