Skip to content
UtilHQ
developer

How to Convert Between YAML and JSON

Learn YAML syntax, JSON comparison, Kubernetes and Docker use cases, common YAML mistakes, and when to choose one format over the other for configuration files.

By UtilHQ Team
Ad Space

YAML and JSON serve the same fundamental purpose: representing structured data as text. But they prioritize different things. JSON prioritizes machine parsing and strict syntax. YAML prioritizes human readability and editing comfort. Both formats appear constantly in modern development workflows, and converting between them is a task developers perform daily.

This guide covers YAML syntax from the ground up, compares it with JSON, walks through real-world use cases, and highlights the mistakes that catch even experienced developers. For quick conversions, use our YAML to JSON Converter.

YAML Syntax Basics

YAML (YAML Ain’t Markup Language) uses indentation and line breaks instead of braces and brackets. Here is a simple YAML document:

name: Alice
age: 30
active: true
address:
  street: 123 Main St
  city: Portland
  state: OR
hobbies:
  - hiking
  - photography
  - cooking

The equivalent JSON:

{
  "name": "Alice",
  "age": 30,
  "active": true,
  "address": {
    "street": "123 Main St",
    "city": "Portland",
    "state": "OR"
  },
  "hobbies": ["hiking", "photography", "cooking"]
}

Core YAML rules:

  1. Key-value pairs use key: value syntax. The space after the colon is required.
  2. Nesting is indicated by indentation. Consistent indentation per level is mandatory.
  3. Lists use - item syntax, with the dash followed by a space.
  4. Strings don’t require quotes unless they contain special characters.
  5. Comments start with # and run to the end of the line. JSON has no comment syntax.
  6. Multiple documents in one file are separated by ---.

YAML Data Types

YAML infers types from values, which is both convenient and dangerous.

ValueYAML TypeJSON Equivalent
helloString"hello"
42Integer42
3.14Float3.14
true / falseBooleantrue / false
null or ~Nullnull
2026-02-09Date"2026-02-09" (string)

The type coercion trap: YAML interprets bare values that look like booleans, numbers, or dates automatically. This creates real problems:

# These are NOT strings in YAML
country: NO        # Boolean false (Norway's ISO code)
version: 1.0       # Float, not string "1.0"
zip: 01234         # Octal number 668, not string "01234"
on: true           # Boolean, not the word "on"

The fix: Quote values that should remain strings:

country: "NO"
version: "1.0"
zip: "01234"
on: "true"

This is one of the most common sources of YAML bugs and a strong reason to convert to JSON when strict typing matters.

JSON vs YAML Comparison

FeatureYAMLJSON
ReadabilityHigh (minimal syntax)Moderate (braces, quotes)
CommentsYes (#)No
Data typesAuto-inferredExplicit
Multiline stringsYes (block scalars)No (use \n)
File sizeSmaller (no braces/quotes)Larger
Parsing speedSlowerFaster
Error-pronenessHigher (indentation issues)Lower (strict syntax)
Spec complexityLarge (200+ pages)Small (10 pages)
Anchors/aliasesYesNo

JSON is a subset of YAML. Every valid JSON document is also valid YAML (since YAML 1.2). The reverse isn’t true because YAML supports features like comments, anchors, and multiline strings that JSON lacks.

Kubernetes and Docker Use Cases

YAML became the dominant configuration format in DevOps largely because of Kubernetes and Docker Compose.

Kubernetes Manifests

Kubernetes resources are defined in YAML files:

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

Converting this to JSON is useful when you need to submit it programmatically via kubectl with the --output=json flag, or when building manifests dynamically in code where JSON libraries are more reliable than YAML generators.

Docker Compose

Docker Compose files define multi-container applications:

version: "3.8"
services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"
    volumes:
      - ./html:/usr/share/nginx/html
    depends_on:
      - api
  api:
    build: ./api
    environment:
      DATABASE_URL: postgres://db:5432/app
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: secret

Developers often convert these to JSON when integrating with CI/CD pipelines that generate configuration programmatically or when validating structure with JSON Schema.

YAML Indentation Rules

Indentation errors account for the majority of YAML parsing failures. The rules are strict:

  1. Spaces only. Tabs aren’t allowed and will throw a parse error. Configure your editor to insert spaces when you press Tab.
  2. Consistent levels. If the first level uses 2 spaces, every level must use 2 spaces. Mixing 2 and 4 spaces at the same nesting level breaks parsing.
  3. Alignment matters. List items at the same level must have their dashes aligned. Object keys at the same level must be aligned.

Correct:

server:
  host: localhost
  port: 8080
  ssl:
    enabled: true
    cert: /etc/ssl/cert.pem

Broken (mixed indentation):

server:
  host: localhost
    port: 8080      # Wrong: 4 spaces instead of 2
  ssl:
   enabled: true    # Wrong: 3 spaces instead of 2

Common YAML Mistakes

Forgetting to Quote Special Strings

The string yes becomes boolean true. The string 3.0 becomes a float. Country codes, version numbers, and timestamps all get silently converted to wrong types.

Duplicate Keys

YAML allows duplicate keys, but the behavior is undefined. Most parsers silently use the last value, discarding earlier ones:

name: Alice
age: 30
name: Bob    # Silently overwrites "Alice"

JSON parsers also handle duplicates inconsistently, but linters catch them more readily.

Multiline String Confusion

YAML offers multiple multiline string syntaxes, and picking the wrong one changes the output:

# Literal block (preserves newlines)
description: |
  Line one
  Line two

# Folded block (joins lines with spaces)
description: >
  Line one
  Line two

# Literal block, strip trailing newline
description: |-
  Line one
  Line two

The | preserves line breaks. The > folds them into spaces. The - suffix strips the trailing newline. Getting these mixed up produces subtly different output that can break downstream processing.

Anchors That Create Circular References

YAML anchors (&name) and aliases (*name) allow reuse:

defaults: &defaults
  timeout: 30
  retries: 3

production:
  <<: *defaults
  timeout: 60

But circular references (anchor A references alias B which references anchor A) crash parsers. JSON has no equivalent feature, so anchors are expanded during conversion.

When to Choose YAML vs JSON

Choose YAML when:

  • Humans will read and edit the file regularly
  • You need comments to document configuration
  • The tool expects YAML (Kubernetes, Ansible, GitHub Actions, Docker Compose)
  • Multiline strings are common (descriptions, scripts)

Choose JSON when:

  • Machines generate and consume the data
  • Strict typing matters (APIs, data interchange)
  • Parsing speed is critical
  • You want minimal ambiguity in data types
  • The file is consumed by JavaScript/TypeScript code

Convert Between Formats

Our YAML to JSON Converter parses YAML with full spec compliance and outputs clean, formatted JSON. Paste your YAML configuration, Kubernetes manifest, or Docker Compose file and get the JSON equivalent immediately.

Frequently Asked Questions

Can I add comments to JSON files?

Standard JSON doesn’t support comments. This is by design: JSON creator Douglas Crockford removed comments to prevent them from being used as parsing directives. Some tools support JSONC (JSON with Comments) or JSON5, which allow // and /* */ style comments, but these are non-standard extensions. If you need comments in your configuration, YAML is the better choice.

Why does my YAML file fail to parse?

The three most common causes are tab characters (use spaces only), inconsistent indentation (every level must use the same number of spaces), and unquoted special values (strings like yes, no, on, off, or values that look like numbers). Run your YAML through a linter to pinpoint the exact line and column of the error.

Is YAML slower to parse than JSON?

Yes. YAML parsing is significantly slower because the specification is more complex. JSON has a simple grammar with about 10 production rules. YAML has over 200 pages of specification covering multiple data types, anchors, tags, and flow styles. For configuration files loaded once at startup, the difference is negligible. For high-throughput data processing with thousands of files, JSON is measurably faster.

Do Kubernetes manifests have to be YAML?

No. Kubernetes accepts both YAML and JSON for all API resources. You can use kubectl apply -f deployment.json the same way you would with a YAML file. YAML is conventional because it’s more readable for human-edited configuration, but programmatically generated manifests often use JSON because it’s easier to produce correctly from code.

What happens to YAML features that JSON doesn’t support?

When converting YAML to JSON, features like comments are stripped (JSON has no comment syntax), anchors and aliases are expanded into their full values, and multiline strings are converted to single strings with \n characters. Date values become strings since JSON has no native date type. The data content is preserved, but the YAML-specific formatting and metadata get lost.

Related Calculators

Share this article

Have suggestions for this article?