Back to Tools

JSON to YAML Converter

Convert JSON to YAML format instantly. You can also convert YAML to JSON by flipping the order.

JSON
0 chars
YAML
0 chars

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy for humans to read and write, and easy for machines to parse and generate. Introduced in the early 2000s, JSON has become the de facto standard for API communication and configuration files.

JSON uses a simple syntax based on key-value pairs:

  • Objects are enclosed in curly braces {}
  • Arrays are enclosed in square brackets []
  • Keys must be strings (enclosed in double quotes)
  • Values can be strings, numbers, booleans, null, objects, or arrays

Why JSON Matters

  • Universal API format: Most REST APIs use JSON for request/response payloads
  • Language agnostic: Supported by virtually every programming language
  • Web-friendly: Native JavaScript support makes it perfect for web applications
  • Structured data: Ideal for configuration files, data storage, and data exchange

What is YAML?

YAML (YAML Ain't Markup Language) is a human-readable data serialization standard. Originally designed for configuration files, YAML emphasizes readability and simplicity.

YAML uses indentation to represent structure:

  • No brackets or braces required (though they're supported)
  • Uses colons : to separate keys from values
  • Uses dashes - to indicate list items
  • Comments start with #
  • Supports multi-line strings with various formatting options

Why YAML Matters

  • Human-readable: Much easier to read and write than JSON for complex configurations
  • Infrastructure as Code: Standard format for Kubernetes, Docker Compose, Ansible, and more
  • Cloud-native: Essential for AWS CloudFormation, Azure ARM templates, and Terraform
  • Comments support: Unlike JSON, YAML supports comments for documentation

Key Differences Between JSON and YAML

FeatureJSONYAML
SyntaxBrackets and bracesIndentation-based
CommentsNot supportedSupported with #
StringsAlways quotedQuoting optional
ReadabilityGood for simple dataExcellent for complex configs
ParsingFasterSlower (more complex)
Use CasesAPIs, web appsConfig files, IaC
Multi-line stringsLimitedRich support

Syntax Comparison

JSON Example:

{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.18.0",
    "lodash": "^4.17.21"
  },
  "scripts": {
    "start": "node server.js",
    "test": "jest"
  }
}

Equivalent YAML:

name: my-app
version: 1.0.0
dependencies:
  express: ^4.18.0
  lodash: ^4.17.21
scripts:
  start: node server.js
  test: jest

Notice how YAML is more compact and readable, especially for nested structures.

Common Use Cases

1. Kubernetes Configuration

Kubernetes manifests are typically written in YAML:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  labels:
    app: my-app
spec:
  containers:
  - name: app-container
    image: nginx:latest
    ports:
    - containerPort: 80

Converting to JSON for API calls:

{
  "apiVersion": "v1",
  "kind": "Pod",
  "metadata": {
    "name": "my-pod",
    "labels": {
      "app": "my-app"
    }
  },
  "spec": {
    "containers": [{
      "name": "app-container",
      "image": "nginx:latest",
      "ports": [{
        "containerPort": 80
      }]
    }]
  }
}

2. Docker Compose Files

Docker Compose uses YAML for service definitions:

version: '3.8'
services:
  web:
    image: nginx
    ports:
      - "80:80"
    environment:
      - NODE_ENV=production
  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: secret

3. AWS CloudFormation Templates

CloudFormation templates can be written in YAML or JSON:

YAML (Preferred):

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-unique-bucket-name

JSON Equivalent:

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Resources": {
    "MyBucket": {
      "Type": "AWS::S3::Bucket",
      "Properties": {
        "BucketName": "my-unique-bucket-name"
      }
    }
  }
}

4. Terraform Configuration

While Terraform uses HCL (HashiCorp Configuration Language), it can export state as JSON, which is often converted to YAML for readability.

5. CI/CD Pipeline Configuration

Many CI/CD tools use YAML for pipeline definitions:

GitHub Actions:

name: CI
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Run tests
      run: npm test

GitLab CI:

stages:
  - build
  - test
  - deploy
 
build:
  stage: build
  script:
    - npm install
    - npm run build

When to Use JSON vs YAML

Use JSON When:

  • API communication: REST APIs, GraphQL responses
  • Web applications: Client-server data exchange
  • Simple configurations: When you don't need comments
  • Performance-critical: JSON parsing is faster
  • JavaScript/TypeScript projects: Native support, no parsing needed

Use YAML When:

  • Configuration files: Application configs, infrastructure definitions
  • Infrastructure as Code: Kubernetes, Docker Compose, CloudFormation
  • Documentation: When you need inline comments
  • Complex nested structures: More readable than deeply nested JSON
  • Human editing: When non-developers need to edit files

Conversion Best Practices

1. Preserve Data Types

Both JSON and YAML support the same data types, but be aware of edge cases:

  • Numbers: JSON numbers are always decimal. YAML supports integers, floats, and scientific notation
  • Booleans: Both support true/false, but YAML also supports yes/no, on/off
  • Null: JSON uses null, YAML uses null, ~, or empty value
  • Strings: JSON requires quotes, YAML quotes are optional unless needed

2. Handle Special Characters

JSON:

{
  "message": "He said \"Hello\"",
  "path": "C:\\Users\\Name"
}

YAML:

message: 'He said "Hello"'
path: "C:\\Users\\Name"

3. Multi-line Strings

YAML has better support for multi-line strings:

YAML:

description: |
  This is a multi-line
  string that preserves
  line breaks.
  
summary: >
  This folds newlines
  into spaces for a
  single paragraph.

JSON Equivalent:

{
  "description": "This is a multi-line\nstring that preserves\nline breaks.\n",
  "summary": "This folds newlines into spaces for a single paragraph.\n"
}

4. Arrays and Lists

JSON:

{
  "tags": ["docker", "kubernetes", "devops"],
  "numbers": [1, 2, 3]
}

YAML (Flow Style):

tags: [docker, kubernetes, devops]
numbers: [1, 2, 3]

YAML (Block Style - Preferred):

tags:
  - docker
  - kubernetes
  - devops
numbers:
  - 1
  - 2
  - 3

Common Conversion Scenarios

Scenario 1: Converting API Response to Config File

You receive a JSON response from an API and need to create a YAML config:

JSON API Response:

{
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "mydb"
  },
  "redis": {
    "host": "localhost",
    "port": 6379
  }
}

YAML Config File:

database:
  host: localhost
  port: 5432
  name: mydb
redis:
  host: localhost
  port: 6379

Scenario 2: Converting Kubernetes Manifest for API

You have a YAML manifest and need to convert it to JSON for the Kubernetes API:

YAML Manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx

JSON for API:

{
  "apiVersion": "apps/v1",
  "kind": "Deployment",
  "metadata": {
    "name": "nginx-deployment"
  },
  "spec": {
    "replicas": 3,
    "selector": {
      "matchLabels": {
        "app": "nginx"
      }
    }
  }
}

Common Mistakes to Avoid

1. Indentation Errors in YAML

YAML is indentation-sensitive. Use consistent spacing (2 or 4 spaces, never tabs):

Wrong:

database:
host: localhost  # Missing indentation
  port: 5432

Correct:

database:
  host: localhost
  port: 5432

2. Trailing Commas in JSON

JSON doesn't allow trailing commas:

Wrong:

{
  "key": "value",
}

Correct:

{
  "key": "value"
}

3. Unquoted Keys in JSON

JSON requires all keys to be quoted strings:

Wrong:

{
  key: "value"
}

Correct:

{
  "key": "value"
}

4. Mixing Data Types

Be careful when converting - ensure data types are preserved:

YAML:

version: 1.0  # Number
enabled: true  # Boolean

JSON:

{
  "version": 1.0,
  "enabled": true
}

5. Special YAML Values

YAML has special values that might not convert as expected:

# These are all null in YAML
null_value: null
tilde_value: ~
empty_value: 
 
# These are all true in YAML
yes_value: yes
on_value: on

Tools and Libraries

Command Line Tools

yq - YAML processor (like jq for JSON):

# Convert YAML to JSON
yq eval -o=json file.yaml
 
# Convert JSON to YAML
yq eval -P file.json

jq - JSON processor:

# Pretty print JSON
cat file.json | jq .
 
# Convert JSON to YAML (requires yq)
cat file.json | jq . | yq eval -P

Programming Languages

JavaScript/Node.js:

const yaml = require('js-yaml');
const fs = require('fs');
 
// YAML to JSON
const doc = yaml.load(fs.readFileSync('file.yaml', 'utf8'));
const json = JSON.stringify(doc, null, 2);
 
// JSON to YAML
const obj = JSON.parse(fs.readFileSync('file.json', 'utf8'));
const yamlStr = yaml.dump(obj);

Python:

import json
import yaml
 
# YAML to JSON
with open('file.yaml', 'r') as f:
    data = yaml.safe_load(f)
    json.dump(data, open('file.json', 'w'), indent=2)
 
# JSON to YAML
with open('file.json', 'r') as f:
    data = json.load(f)
    yaml.dump(data, open('file.yaml', 'w'), default_flow_style=False)

Frequently Asked Questions

Can I convert any JSON to YAML?

Yes, any valid JSON can be converted to YAML. However, some JSON features (like trailing commas) will need to be fixed first.

Can I convert any YAML to JSON?

Most YAML can be converted to JSON, but some YAML-specific features may be lost:

  • Comments are removed
  • Multi-line string formatting may change
  • Special YAML values (like yes, no, ~) are converted to their JSON equivalents

Which is faster: JSON or YAML parsing?

JSON parsing is generally faster because it has a simpler syntax. YAML parsing is more complex due to indentation handling and special features.

Can I use both in the same project?

Yes! Many projects use JSON for API communication and YAML for configuration files. For example:

  • Kubernetes: YAML manifests, JSON API responses
  • Docker: YAML Compose files, JSON container configs
  • CI/CD: YAML pipeline definitions, JSON build artifacts

How do I handle large files?

For very large files (hundreds of MB), consider:

  • Streaming parsers instead of loading entire file into memory
  • Converting in chunks if possible
  • Using command-line tools like yq or jq for better performance

Are there security concerns?

Yes, be careful when parsing untrusted YAML or JSON:

  • YAML: Can execute arbitrary code if using unsafe loaders (use safe_load in Python, safeLoad in JavaScript)
  • JSON: Generally safer, but large files can cause memory issues
  • Always validate and sanitize input from untrusted sources

Additional Resources