Skip to content
Data2026-06-01Begin13 min read

Complete Guide to YAML JSON Conversion: Principles, Tools, and Pitfalls

What Are YAML and JSON

In modern software development, data serialization formats are everywhere. YAML and JSON are two of the most commonly used structured data representation formats, each with its own characteristics and suitable for different scenarios.

What Is YAML

YAML (YAML Ain't Markup Language) is a human-friendly data serialization standard first proposed by Clark Evans in 2001. Its design goal is to make data both easy for humans to read and write, and easy for machines to parse and generate.

Core features of YAML:

  • Highly readable: Uses indentation to represent hierarchy, similar to Python syntax
  • Clean syntax: No need for quotes, braces, or other redundant symbols
  • Rich data types: Supports strings, numbers, booleans, dates, null values, lists, dictionaries, and more
  • Advanced features: Supports anchors (&), aliases (*), multi-line strings, complex keys, etc.
  • Comments supported: You can use # to add comments for documentation

A simple YAML example:

name: ToolVault
description: Developer online toolkit
version: 2.0
features:
  - Format conversion
  - Encoding & decoding
  - Text processing
  - Crypto & hashing
is_free: true
founded: 2024-01-15

What Is JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format popularized by Douglas Crockford around 2001. A JSON-to-YAML converter is often used when converting API responses into config files. It originated from the JavaScript language but has now become a universal format supported by almost all programming languages.

Core features of JSON:

  • Concise syntax: Uses braces {} and brackets [] to represent structure
  • Machine-friendly: Fast parsing, native support in almost all languages
  • Limited data types: Supports objects, arrays, strings, numbers, booleans, and null
  • No comments: Standard JSON does not support comments
  • Strict format: Keys must be in double quotes, strings must be in double quotes

The same content as JSON:

{
  "name": "ToolVault",
  "description": "Developer online toolkit",
  "version": 2.0,
  "features": ["Format conversion", "Encoding & decoding", "Text processing", "Crypto & hashing"],
  "is_free": true,
  "founded": "2024-01-15"
}

Relationship and Differences

YAML and JSON are closely related: JSON is syntactically a subset of YAML 1.2, meaning almost all valid JSON is valid YAML. This is why YAML parsers can usually parse JSON data directly.

But there is a frequently ignored prerequisite: this only strictly holds under YAML 1.2's JSON schema. An input like {"flag": on} is valid JSON-as-YAML-1.2 text, but a YAML 1.1-style parser will read on as boolean true — the syntax is a subset, the scalar interpretation is not. The "YAML 1.1 vs 1.2" section below expands on this.

However, many features of YAML do not exist in JSON, such as comments, anchors, and multi-line strings.

Why Convert Between YAML and JSON

In actual development, converting between YAML and JSON is a very common requirement. Here are several typical application scenarios.

Configuration File Scenarios

YAML is widely used as a configuration file format due to its good readability:

  • Kubernetes: All resource definitions (Deployment, Service, ConfigMap, etc.) use YAML
  • Docker Compose: Container orchestration configuration file docker-compose.yml
  • Ansible: Automated operations Playbooks are written in YAML
  • GitHub Actions: CI/CD workflow configuration
  • OpenAPI/Swagger: API documentation specifications are usually written in YAML

The internal implementations of these configuration tools often parse YAML into JSON structures before processing.

API Data Exchange

In the Web API domain, JSON is the de facto standard data exchange format. When you need to:

  • Send YAML-configured content to the backend via API
  • Save JSON data returned by the API as a YAML configuration file
  • Transfer data between YAML-supporting tools and JSON-supporting systems

These scenarios all require format conversion.

Frontend and Backend Collaboration

Frontend developers are usually more familiar with JSON, while backend or DevOps engineers may be more accustomed to writing configurations in YAML. In team collaboration, it's often necessary to:

  • Backend provides JSON API responses, frontend needs to convert to YAML for configuration
  • DevOps writes configurations in YAML, developers need to convert to JSON for use in code
  • Technical documentation provides examples in both formats

YAML vs JSON Comparison

Let's take a detailed comparison table to fully understand the differences between these two formats.

Syntax Comparison Table

FeatureYAMLJSON
Syntax StyleIndentation represents hierarchyBraces and brackets
CommentsSupported (#)Not supported
String QuotesOptional, not needed in most casesMust use double quotes
Key QuotesOptionalMust use double quotes
Multi-line StringsNatively supported (`, >`)
Data TypesRich (dates, times, null, etc.)Limited (6 basic types)
Anchors/AliasesSupported (&, *)Not supported
File Extensions.yaml / .yml.json
Human ReadabilityHighMedium
Parsing SpeedRelatively slowFast
Language SupportRequires third-party librariesNative support in most languages

Advantages and Use Cases

YAML advantages:

  • More suitable for human reading and writing
  • Supports comments for documentation
  • More natural multi-line string handling
  • Can use anchors and aliases to reduce repetition
  • Suitable as a configuration file format

JSON advantages:

  • Faster parsing speed
  • Native support in almost all programming languages
  • Strict syntax, less prone to ambiguity
  • Suitable as an API data exchange format
  • More mature tool ecosystem

In short: use YAML for config files, use JSON for data exchange.

Methods for YAML to JSON Conversion

Here are several common YAML to JSON conversion methods, from the simplest online tools to CLI and code implementations.

Online Tool Conversion

The quickest way is to use an online conversion tool, no need to install any software.

Using ToolVault YAML JSON Converter:

  1. Paste YAML content in the left input box
  2. The converted JSON automatically appears on the right in real-time
  3. Click the copy button to get the result

This method is suitable for temporary conversions, quick validation, and scenarios where you don't want to install tools.

Command Line Tools

For developers, command line tools are more efficient, especially for batch processing.

Using yq

yq is a command-line tool specifically for processing YAML, similar to jq for JSON.

# Convert YAML file to JSON
yq eval -o=json input.yaml > output.json

# Or use shorthand
yq -o=json input.yaml

Using Python

Python standard library comes with JSON module, YAML requires installing PyYAML:

# Install PyYAML
pip install pyyaml

# One-liner conversion
python -c "import yaml, json, sys; print(json.dumps(yaml.safe_load(sys.stdin), indent=2))" < input.yaml > output.json

Programming Language Implementations

Converting in project code is the most flexible approach.

JavaScript / Node.js

Using the js-yaml library:

npm install js-yaml
const fs = require('fs');
const yaml = require('js-yaml');

const yamlContent = fs.readFileSync('input.yaml', 'utf8');
const data = yaml.load(yamlContent);
const jsonContent = JSON.stringify(data, null, 2);

console.log(jsonContent);

Python

import yaml
import json

with open('input.yaml', 'r', encoding='utf-8') as f:
    data = yaml.safe_load(f)

with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

Tip: Use yaml.safe_load() instead of yaml.load() to avoid YAML deserialization security issues.

Methods for JSON to YAML Conversion

JSON to YAML conversion also has various implementation methods.

Online Tools

Using online tools is one of the fastest ways.

ToolVault YAML JSON Converter supports bidirectional conversion:

  1. Click the "Switch direction" button in the middle to switch to JSON → YAML mode
  2. Enter JSON content on the left
  3. The converted YAML appears on the right in real-time

Command Line

Using yq

# Convert JSON file to YAML
yq eval -P input.json > output.yaml

Using Python

python -c "import yaml, json, sys; print(yaml.dump(json.load(sys.stdin), allow_unicode=True, default_flow_style=False))" < input.json > output.yaml

Code Implementation

JavaScript / Node.js

const fs = require('fs');
const yaml = require('js-yaml');

const jsonContent = fs.readFileSync('input.json', 'utf8');
const data = JSON.parse(jsonContent);
const yamlContent = yaml.dump(data, { indent: 2, lineWidth: -1 });

console.log(yamlContent);

Python

import json
import yaml

with open('input.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

with open('output.yaml', 'w', encoding='utf-8') as f:
    yaml.dump(data, f, allow_unicode=True, default_flow_style=False, sort_keys=False)

Common Problems and Pitfalls

Converting between YAML and JSON seems simple, but various problems are often encountered in practice. Here are some of the most common pitfalls.

Indentation Issues

YAML is very sensitive to indentation, which is the most common pitfall for beginners:

  • Must use spaces for indentation, cannot use Tab
  • Indentation at the same level must be aligned
  • Usually 2 or 4 spaces are commonly used, but be consistent within a file
# Correct
person:
  name: Alice
  age: 30

# Wrong: inconsistent indentation
person:
  name: Alice
   age: 30  # one extra space

Solution: Use an editor that supports YAML, enable show whitespace characters feature; or use ToolVault's YAML formatter to automatically fix formatting.

Data Type Loss

YAML's automatic type inference can sometimes cause surprises. But one key fact first: most of these traps belong to YAML 1.1 parsing behavior. YAML 1.2 (published 2009) tightened booleans to only true / false, made integers decimal-only, and turned yes/no/on/off, leading-zero octals, and sexagesimal back into plain strings. New-generation parsers (go-yaml v3, js-yaml, ruamel.yaml, yamllint) all parse by 1.2 rules; the famous holdout still parsing 1.1-style is PyYAML.

Measured with js-yaml 5.x (the library behind this tool, default DEFAULT_SCHEMA, YAML 1.2 core schema):

# YAML 1.1 parsers (e.g. PyYAML)               # js-yaml / YAML 1.2
enabled: yes      # -> true (boolean)           # -> "yes" (string)
flag: off         # -> false                    # -> "off"
port: 08080       # -> 520 (leading-0 octal!)   # -> 8080 (decimal)
base: 0o17        # -> 15                       # -> 15 (0o octal still valid)
date: 2024-01-15  # -> Date object              # -> string "2024-01-15"

Note that under js-yaml, 2024-01-15 parses as a string (the core schema has no date type), not a Date object — some tutorials claim YAML converts dates to Date, but that is library- and version-specific behavior.

The Norway Problem

YAML 1.1's boolean vocabulary is notorious: y / n / yes / no / true / false / on / off in various capitalizations — 22 spellings in total. Hence:

countries:
  - NO   # Norway's country code; parsed as false under YAML 1.1!
  - CN

Migrating a country list between a YAML 1.1 system and a YAML 1.2 system (or vice versa) makes NO drift between boolean false and string "NO" — this is what the config community calls "the Norway problem". Values like 1:30 also bite: YAML 1.1 reads them as sexagesimal (90). Docker Compose's unquoted ports entry 8080:80 hit exactly this trap (see the quoting discussion in the docker run to compose guide).

Solutions:

  • Always quote values that must stay strings: port: "08080", enabled: "yes", country: "NO"
  • Upgrade toolchains to YAML 1.2 parsing (go-yaml v3+, js-yaml, ruamel.yaml); watch out that PyYAML still behaves as 1.1 to this day
  • After conversion, validate types with something like JSON Schema instead of eyeballing

Circular References

JSON does not support circular references, but objects in languages like JavaScript may have them. There are two sources: cycles constructed by hand in business code, and shared structures that YAML anchors/aliases naturally produce after parsing (see the anchor section above):

const obj = { name: 'test' };
obj.self = obj;  // circular reference
JSON.stringify(obj);  // Error: TypeError: Converting circular structure to JSON

Solution:

  • Avoid using circular references in data that needs to be serialized
  • Use specialized libraries to handle circular references (like circular-json, though deprecated)

Multi-line String Handling

YAML has multiple syntaxes for multi-line strings, attention is needed during conversion:

# | preserves newlines
description: |
  First line
  Second line

# > folds newlines (into spaces)
summary: >
  This is a
  very long text

After converting to JSON:

{
  "description": "First line\nSecond line\n",
  "summary": "This is a very long text\n"
}

Note: The | and > syntax handle trailing newlines differently, choose according to your actual needs.

YAML Anchors and Aliases Can't Be Converted to JSON

YAML's anchors (&) and aliases (*) are very useful features that can reduce repetition:

defaults: &defaults
  adapter: postgres
  host: localhost

development:
  <<: *defaults
  database: dev_db

production:
  <<: *defaults
  database: prod_db

With the merge key <<: *defaults above, development ends up with all three fields adapter, host, database. But JSON has no anchors or merge keys, so conversion produces a fully expanded structure. The data is correct, but the "reference" semantics are lost.

The merge key << has sharp edges. It is not part of the YAML 1.2 core spec — just an optional tag from the type repository — so parser support varies:

  • PyYAML and go-yaml v3 support merge keys; development correctly gets all three fields
  • js-yaml also supports << merging, but only when the merge key sits directly under a mapping; inside an inline flow mapping (x: {<<: *d, b: 2}) it is treated as a plain key literally named <<
  • Cross-document anchors are forbidden: an alias may only reference an anchor defined earlier in the same document; referencing doc1's anchor from doc2 in a multi-document stream is an error

Three more anchor boundaries worth knowing:

  1. Aliases are shared references, not copies. In JavaScript, the object resolved from *defaults is the same in-memory object as &defaults. If aliases form a cycle (a: &x { self: *x }), JSON.stringify throws Converting circular structure to JSON — one source of the circular-reference problem covered below.
  2. Anchors can be redefined. A later &defaults in the same document overrides the earlier one; an alias resolves to the most recent anchor before it.
  3. To change a single field per environment, use the merge key rather than appending keys after an alias.

Solution: If you need to preserve reference relationships, handle it in your business code, or choose a format that supports references. Before converting, expand anchors with yamllint or your parser to confirm the result matches expectations.

Multi-Document Streams (--- / ...)

Kubernetes manifests, Helm templates, and CI configs often pack several YAML documents into one file, separated by --- and optionally closed by ...:

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app

This structure is unique to YAML; JSON has no equivalent. Tools handle it very differently:

  • js-yaml's load() throws on multi-document input (expected a single document in the stream) — that is deliberate design, not a bug, to prevent silently dropping data
  • To convert multi-doc, use loadAll() to get an array, then JSON.stringify each document
  • yq emits one JSON per document by default; jq -s collects them into an array
  • The Kubernetes toolchain (kubectl apply -f) accepts multi-document streams natively

Practical advice: when converting multi-document YAML to JSON, confirm whether the consumer expects a "JSON array" or "JSON Lines"; both are common. When a single-document converter errors at a --- line, check whether the input is multi-document first.

Troubleshooting Common Lint / Parse Errors

YAML error messages usually carry line and column numbers, but a few causes are unintuitive:

Error (js-yaml wording)Real causeWhat to do
bad indentation of a mapping entryInconsistent indentation of sibling keys, or mixed tabsEnable "show whitespace" in your editor; convert all tabs to spaces
duplicated mapping keySame key twice in one mapping (js-yaml and yamllint error by default; PyYAML silently lets the later value win)Search for duplicated key names; common in multi-author CI configs
unexpected end of the stream within a flow collectionUnclosed [ or {Walk backwards from the reported line looking for the open bracket
can not read an implicit mapping pair; a colon is missedValue contains : (colon+space) without quotes, e.g. time: 10:30Quote values containing colons: time: "10:30"
missed comma between flow collection entriesSpecial characters in a flow-style key: valueSame fix: quote it, or switch to block style

General triage order: run yamllint -d relaxed file.yaml first; if the reported line makes no sense, shrink the file to a minimal fragment around it and re-parse; if still stuck, quote every suspicious value — most mysterious YAML parse errors can be explained and fixed by "add quotes".

Using ToolVault Online YAML JSON Converter

If you need to convert between YAML and JSON quickly and conveniently, ToolVault's online YAML JSON Converter is an excellent choice.

Bidirectional Conversion

The tool supports both YAML → JSON and JSON → YAML bidirectional conversion, switch direction with one click, meeting various conversion needs. Whether converting configuration files to JSON for API use, or saving interface-returned data as YAML configuration, it's easily done.

Real-time Preview

As you type, the results on the right update in real-time, no need to click a convert button. You can see the conversion results as you write, quickly verifying whether the format is correct.

Format Validation

The tool automatically detects syntax errors and provides clear error messages to help you quickly locate problems. Whether it's YAML indentation issues or JSON syntax errors, everything is clear at a glance.

Additionally, the tool also supports:

  • Formatting & beautification: Automatically adjust indentation and line breaks for more readable code
  • Compression / minification: JSON can be converted to compressed format to reduce size
  • Big-integer protection: On the JSON → YAML direction, integers beyond the safe range are automatically stringified, so Snowflake-style IDs are not silently rewritten (see the implementer's note below)
  • One-click copy: Convert results with one click to clipboard
  • Pure client-side operation: All processing done locally in the browser, data is not uploaded to a server, protecting privacy

Best Practices

1. Choose the Right Format

  • Configuration files: Prefer YAML, good readability, supports comments
  • API data exchange: Use JSON, good compatibility, fast parsing
  • Storing large amounts of data: Consider more compact formats (like MessagePack, Protocol Buffers)

2. Maintain Consistent Style

Within the same project, maintain consistency in formatting style:

  • YAML indentation uniformly uses 2 spaces or 4 spaces
  • JSON indentation space count consistent
  • Naming style unified (camelCase, snake_case, kebab-case — pick one)

3. Pay Attention to Data Types

  • If a string might be misinterpreted as a number, boolean, or date, be sure to add quotes
  • Pay attention to floating point precision issues, especially with monetary data
  • For null values, uniformly use null (JSON) or null / ~ (YAML)

4. Validate After Conversion

After the conversion is complete, don't use it directly, first verify:

  • Check whether key field values are correct
  • Verify that no unexpected data type changes have occurred
  • Confirm no fields or data are missing

5. Parse YAML Safely

  • Always use safe_load instead of load to avoid deserialization attacks
  • Don't parse YAML files from untrusted sources
  • Validate the parsed data for legitimacy

FAQ

Which is better: YAML or JSON?

There's no absolute "better" — it depends on the use case. For configuration files, YAML is recommended (good readability, supports comments). For API data exchange, JSON is recommended (good compatibility, fast parsing).

Why does my YAML file sometimes fail to parse?

The most common cause is indentation issues. YAML is very sensitive to indentation — you must use spaces (not Tabs), and indentation at the same level must be strictly aligned. Additionally, special characters and unquoted strings can also cause parsing errors.

Does JSON support comments?

Standard JSON does not support comments. However, some tools and libraries (like JSON5, JSONC) extend JSON syntax to support comments. If you need configuration files with comments, we recommend using YAML directly.

Why do data types change after YAML to JSON conversion?

First pin down the direction: did the type change at parse time (a YAML 1.1-style parser turning yes into true or 08080 into 520), or at serialization time (a Date object stringified by toJSON, or a big integer beyond 2^53 being truncated)? The former is fixed by quoting values or upgrading the parser; the latter requires preprocessing the data before conversion. For any string that might be misread, quoting everything is the cheapest defense.

Why does my multi-document YAML fail to convert to JSON?

Single-document converters (like js-yaml's load()) throw expected a single document in the stream when they meet a ----separated stream. Switch to a multi-document API (loadAll()) or use yq, which emits one JSON per document; if a converter only converts the first document, make sure it is not silently dropping the rest.

Is there a way to do batch conversion?

Yes. You can use command-line tools (like yq) with shell scripts to batch process files, or write scripts in Python/Node.js to traverse directories for conversion. For simple temporary conversions, you can also use online tools to process them one by one.

Implementer's Note (actual behavior of this site's converter)

This section describes the real implementation behind this tool (js-yaml 5.2.1, via the two pure functions yamlToJson / jsonToYaml). Other online tools or local libraries may behave differently — trust your own measurements:

  • YAML → JSON: yaml.load() (1.2 core schema) → JSON.stringify(obj, null, 2). Anchors, aliases and merge keys are expanded into plain objects during parsing; multi-document streams throw expected a single document in the stream instead of converting only the first document; duplicate keys fail fast with duplicated mapping key.
  • JSON → YAML: a purpose-built lossless parser (parseLossless, based on the meriyah AST) preserves every numeric token verbatim, then integers beyond Number.MAX_SAFE_INTEGER are written into YAML as strings (js-yaml's dump has no lossless number type). So {"id": 2099774875233849345} becomes id: '2099774875233849345' — the 19-digit Snowflake ID keeps its digits, but its type changes from number to string; downstream consumers should be aware.
  • The reverse direction is asymmetric: such a stringified big integer comes back from YAML → JSON as a string, not the original number; only integers within ±2^53 round-trip losslessly. The full discussion is in JSON Integer Precision Trap.
  • Default dump options: indent: 2, lineWidth: 120 — strings longer than 120 characters are folded onto new lines; this is not a data change, so don't be surprised in diffs.
  • Pure client-side: all conversion runs locally in your browser; nothing is uploaded.

Further Reading


This article is provided by ToolVault. Try our online YAML JSON converter now and make data format conversion simple and efficient. Visit the homepage for more developer tools.