DevToolBoxGRATIS
Blog

Convertitore YAML in JSON: Guida Completa con Esempi di Codice

12 min di letturadi DevToolBox

YAML to JSON conversion is one of the most common data format tasks developers face daily. Whether you are managing Kubernetes manifests, Docker Compose files, CI/CD pipelines, or application configuration, you frequently need to convert YAML to JSON and back. YAML (YAML Ain't Markup Language) is prized for its human-readable, indentation-based syntax, while JSON (JavaScript Object Notation) dominates APIs and programmatic data exchange. This comprehensive guide covers everything you need to know about yaml to json converter tools, the parsing process, code examples in four languages, common pitfalls, and best practices. If you need a quick yaml to json online conversion, try our free tool below.

Try our free online YAML to JSON / JSON to YAML converter instantly.

What Is YAML?

YAML (YAML Ain't Markup Language) is a human-friendly data serialization language used extensively for configuration files and data exchange. Originally standing for "Yet Another Markup Language," the recursive acronym was later changed to emphasize that YAML is about data, not document markup. A yaml parser reads the indentation-based structure and converts it into native data structures like dictionaries, lists, and scalars.

YAML uses whitespace indentation (spaces only, never tabs) to denote structure, making it visually clean and easy to read. It supports scalar types (strings, integers, floats, booleans, null), sequences (arrays/lists), and mappings (dictionaries/objects). Advanced features include anchors and aliases for reusing data, multi-line strings with block scalars (| for literal, > for folded), and multiple documents in a single file separated by ---. The yaml syntax is designed to be a superset of JSON, meaning every valid JSON document is also valid YAML.

YAML is the preferred format for Kubernetes manifests, Ansible playbooks, Docker Compose files, GitHub Actions workflows, Swagger/OpenAPI specifications, Spring Boot configuration, and many other DevOps and cloud-native tools. Its readability advantage over JSON makes it the go-to choice for files that humans edit frequently, while JSON remains preferred for machine-to-machine communication and APIs.

YAML vs JSON: Key Differences

Understanding the differences between YAML and JSON helps you choose the right format and avoid conversion pitfalls. Here is a detailed comparison:

FeatureYAMLJSON
SyntaxIndentation-based, no brackets or braces requiredBracket and brace delimited ({}, [])
CommentsSupports comments with #No comment support
Data typesStrings, ints, floats, bools, null, dates, binaryStrings, numbers, booleans, null, arrays, objects
Multi-line stringsBlock scalars: | (literal) and > (folded)Must use \n escape sequences
Anchors & aliasesSupported with & and * for data reuseNot supported
Multiple documentsYes, separated by ---No (one value per file)
ReadabilityHighly readable, minimal punctuationMore verbose with quotes and braces
File sizeGenerally smaller (no quotes or braces)Slightly larger due to syntax characters
Parsing speedSlower (indentation-sensitive parsing)Faster (simpler grammar)
ToolingGood support; yamllint, yq, PyYAMLUniversal support; native in all languages

How YAML to JSON Conversion Works

When you use a yaml to json converter, the tool performs a multi-step parsing and serialization process. Understanding these steps helps you debug conversion issues and handle edge cases correctly.

Step 1: Lexical Analysis (Tokenization) — The yaml parser scans the raw YAML text character by character, identifying tokens such as indentation levels, key-value separators (:), sequence indicators (-), block scalar indicators (|, >), anchors (&), aliases (*), tags, and scalar values. Unlike JSON parsing, YAML tokenization must track indentation depth to determine nesting.

Step 2: Parsing (AST Construction) — Tokens are assembled into an Abstract Syntax Tree (AST) that represents the hierarchical structure. Mappings become object nodes, sequences become array nodes, and scalars become leaf nodes. Anchors are stored for later resolution when aliases reference them.

Step 3: Composing (Native Data Structures) — The AST is converted into the programming language's native data structures: YAML mappings become JSON objects (or language dictionaries/maps), YAML sequences become JSON arrays (or language lists), and YAML scalars are type-resolved. This is where implicit type conversion occurs: true/false/yes/no become booleans, unquoted numbers become integers or floats, null/~ become null, and dates like 2024-01-15 may become date objects.

Step 4: JSON Serialization — Finally, the native data structures are serialized into JSON text using JSON.stringify(), json.dumps(), or equivalent. Multi-document YAML files (separated by ---) are typically converted into a JSON array where each element represents one document. YAML comments are discarded since JSON has no comment syntax. Anchors and aliases are fully resolved (dereferenced) into their expanded form.

YAML to JSON Code Examples

JavaScript / Node.js (js-yaml)

The js-yaml library is the most popular yaml parser for JavaScript and Node.js. It provides yaml.load() to parse YAML into JavaScript objects and yaml.dump() for the reverse. Combined with the native JSON.stringify(), you get a complete yaml to json converter:

// ===== YAML to JSON (Node.js) =====
const yaml = require('js-yaml');
const fs = require('fs');

// Parse YAML string to JavaScript object
const yamlString = `
server:
  host: localhost
  port: 8080
  ssl: true
database:
  name: myapp
  replicas:
    - host: db1.example.com
      port: 5432
    - host: db2.example.com
      port: 5432
  # Connection pool settings
  pool:
    min: 5
    max: 20
`;

const data = yaml.load(yamlString);
const json = JSON.stringify(data, null, 2);
console.log(json);
// {
//   "server": {
//     "host": "localhost",
//     "port": 8080,
//     "ssl": true
//   },
//   "database": {
//     "name": "myapp",
//     "replicas": [
//       { "host": "db1.example.com", "port": 5432 },
//       { "host": "db2.example.com", "port": 5432 }
//     ],
//     "pool": { "min": 5, "max": 20 }
//   }
// }

// ===== JSON to YAML =====
const jsonData = { name: 'app', version: '2.0', features: ['auth', 'logging'] };
const yamlOutput = yaml.dump(jsonData, { indent: 2 });
console.log(yamlOutput);
// name: app
// version: '2.0'
// features:
//   - auth
//   - logging

// ===== Read YAML file and convert to JSON =====
const fileContent = fs.readFileSync('config.yaml', 'utf8');
const config = yaml.load(fileContent);
fs.writeFileSync('config.json', JSON.stringify(config, null, 2));

// ===== Handle multi-document YAML =====
const multiDoc = `
---
name: doc1
---
name: doc2
`;
const docs = yaml.loadAll(multiDoc);
console.log(JSON.stringify(docs, null, 2));
// [{ "name": "doc1" }, { "name": "doc2" }]

Python (PyYAML)

Python's PyYAML library is the standard yaml parser for Python. Always use yaml.safe_load() instead of yaml.load() to prevent arbitrary code execution from untrusted YAML. Combined with json.dumps(), you can convert yaml to json in just two lines:

import yaml
import json

# ===== YAML to JSON =====
yaml_string = """
server:
  host: localhost
  port: 8080
  ssl: true
database:
  name: myapp
  replicas:
    - host: db1.example.com
      port: 5432
    - host: db2.example.com
      port: 5432
  pool:
    min: 5
    max: 20
"""

# Always use safe_load (prevents arbitrary code execution)
data = yaml.safe_load(yaml_string)
json_output = json.dumps(data, indent=2, ensure_ascii=False)
print(json_output)

# ===== JSON to YAML =====
json_string = '{"name": "app", "version": "2.0", "features": ["auth", "logging"]}'
json_data = json.loads(json_string)
yaml_output = yaml.dump(json_data, default_flow_style=False, allow_unicode=True)
print(yaml_output)

# ===== File conversion =====
# YAML file to JSON file
with open('config.yaml', 'r') as yf:
    config = yaml.safe_load(yf)
with open('config.json', 'w') as jf:
    json.dump(config, jf, indent=2)

# JSON file to YAML file
with open('data.json', 'r') as jf:
    data = json.load(jf)
with open('data.yaml', 'w') as yf:
    yaml.dump(data, yf, default_flow_style=False)

# ===== Handle multi-document YAML =====
multi_yaml = """
---
name: doc1
type: config
---
name: doc2
type: data
"""
docs = list(yaml.safe_load_all(multi_yaml))
print(json.dumps(docs, indent=2))

# ===== Preserve key order (Python 3.7+) =====
# dict maintains insertion order by default
ordered = yaml.safe_load(yaml_string)
print(json.dumps(ordered, indent=2))  # keys stay in YAML order

Bash / CLI (yq, python one-liner)

For command-line yaml to json conversion, yq (a YAML processor similar to jq) is the most efficient tool. You can also use Python or Ruby one-liners for quick conversions without installing extra tools:

# ===== yq: YAML processor (like jq for YAML) =====

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

# Convert YAML to JSON and save to file
yq -o=json config.yaml > config.json

# Convert JSON to YAML
yq -P config.json

# Convert JSON to YAML and save
yq -P config.json > config.yaml

# Extract a specific field from YAML as JSON
yq -o=json '.server.port' config.yaml

# ===== Python one-liner =====

# YAML to JSON (stdin)
cat config.yaml | python3 -c \
  'import sys,yaml,json; json.dump(yaml.safe_load(sys.stdin),sys.stdout,indent=2)'

# YAML to JSON (file)
python3 -c \
  'import yaml,json; print(json.dumps(yaml.safe_load(open("config.yaml")),indent=2))'

# JSON to YAML
cat data.json | python3 -c \
  'import sys,yaml,json; print(yaml.dump(json.load(sys.stdin),default_flow_style=False))'

# ===== Ruby one-liner =====
ruby -ryaml -rjson -e 'puts JSON.pretty_generate(YAML.load($stdin.read))' < config.yaml

# ===== Pipe YAML from curl to JSON =====
curl -s https://raw.githubusercontent.com/example/repo/main/config.yaml | \
  yq -o=json

# ===== Validate YAML before converting =====
yamllint config.yaml && yq -o=json config.yaml

Go (gopkg.in/yaml.v3)

In Go, the gopkg.in/yaml.v3 package provides robust YAML parsing. Go's strong typing makes the yaml to json conversion explicit. You unmarshal YAML into an interface{} and then marshal it back as JSON:

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "gopkg.in/yaml.v3"
)

func main() {
    // YAML input string
    yamlData := []byte(`
server:
  host: localhost
  port: 8080
  ssl: true
database:
  name: myapp
  replicas:
    - host: db1.example.com
      port: 5432
    - host: db2.example.com
      port: 5432
`)

    // Parse YAML into interface{}
    var data interface{}
    err := yaml.Unmarshal(yamlData, &data)
    if err != nil {
        log.Fatalf("YAML parse error: %v", err)
    }

    // Convert map[string]interface{} keys for JSON compatibility
    data = convertMapKeys(data)

    // Marshal to JSON
    jsonData, err := json.MarshalIndent(data, "", "  ")
    if err != nil {
        log.Fatalf("JSON marshal error: %v", err)
    }
    fmt.Println(string(jsonData))
}

// convertMapKeys recursively converts map[interface{}]interface{}
// to map[string]interface{} for JSON compatibility
func convertMapKeys(v interface{}) interface{} {
    switch v := v.(type) {
    case map[string]interface{}:
        result := make(map[string]interface{})
        for key, val := range v {
            result[key] = convertMapKeys(val)
        }
        return result
    case []interface{}:
        for i, val := range v {
            v[i] = convertMapKeys(val)
        }
        return v
    default:
        return v
    }
}

JSON to YAML Conversion

The reverse direction — json to yaml converter — is equally important. When you receive JSON from an API and need to store it in a YAML configuration file, or when you want to make a JSON document more human-readable, converting JSON to YAML is the solution. Every major YAML library supports this direction natively.

Key consideration: comments are lost. If you convert a commented YAML file to JSON and back to YAML, all comments will be permanently lost because JSON has no comment syntax. This is the most common complaint about round-trip conversion. To preserve comments, use specialized tools like ruamel.yaml in Python or yaml CST (Concrete Syntax Tree) parsers that maintain the original formatting.

Best practices for JSON to YAML conversion: (1) Use 2-space indentation for consistency with Kubernetes and Docker conventions. (2) Avoid flow style ({} and []) in output for maximum readability. (3) Quote strings that could be misinterpreted as other types (e.g., "yes", "3.14", "null"). (4) Validate the output with a yaml validator to catch indentation or syntax errors.

Common YAML Pitfalls and Edge Cases

YAML's flexibility introduces several gotchas that catch even experienced developers. Understanding these pitfalls helps you write correct YAML and avoid bugs when using a yaml to json converter:

Tabs vs. Spaces — YAML forbids tabs for indentation. Using tabs will cause a parse error. Always configure your editor to insert spaces (typically 2) when pressing Tab in YAML files. A yaml validator will immediately catch tab characters.

The Boolean Trap — YAML 1.1 (used by many parsers including PyYAML) interprets a surprisingly large set of values as booleans: yes, no, on, off, true, false, y, n (case-insensitive). This means a country code like NO (Norway) or a value like on becomes a boolean true or false in JSON. Always quote strings that could be misread: "NO", "yes", "on". YAML 1.2 restricts booleans to only true and false, but many parsers still default to 1.1 behavior.

# The YAML boolean trap - these all become true or false in JSON!

# YAML 1.1 boolean values (case-insensitive):
is_active: yes        # → true
is_active: no         # → false
is_active: on         # → true
is_active: off        # → false
is_active: y          # → true
is_active: n          # → false
is_active: true       # → true
is_active: false      # → false

# Real-world problems:
countries:
  - US                # string "US" ✓
  - GB                # string "GB" ✓
  - NO                # boolean false ✗ (Norway disappears!)
  - FR                # string "FR" ✓

# Fix: always quote ambiguous values
countries:
  - "US"
  - "GB"
  - "NO"              # string "NO" ✓
  - "FR"

# Version numbers are also problematic:
version: 1.0          # → float 1 (not string "1.0")
version: "1.0"        # → string "1.0" ✓

Multiline Strings — YAML offers multiple ways to write multiline strings, each with subtle differences. The literal block scalar | preserves newlines exactly as written. The folded block scalar > replaces single newlines with spaces (like HTML). Chomping indicators control trailing newlines: |+ keeps all trailing newlines, |- strips all trailing newlines, and | (default) keeps one trailing newline. Misunderstanding these produces unexpected whitespace in your JSON output.

# YAML multiline string variants

# Literal block scalar (|) - preserves newlines
description: |
  This is line one.
  This is line two.
  This is line three.
# JSON: "This is line one.\nThis is line two.\nThis is line three.\n"

# Folded block scalar (>) - replaces newlines with spaces
description: >
  This is a long
  paragraph that will
  be folded into one line.
# JSON: "This is a long paragraph that will be folded into one line.\n"

# Chomping indicators:
keep_trailing: |+     # Keep ALL trailing newlines
  text

strip_trailing: |-    # Strip ALL trailing newlines
  text

clip_trailing: |      # Keep exactly ONE trailing newline (default)
  text

Special Characters in Keys and Values — Colons, hashes, brackets, and braces in YAML values must be quoted to avoid parsing errors. For example, url: https://example.com works, but message: Hello: World fails because the parser sees a second key. Use quotes: message: "Hello: World". Similarly, values starting with {, [, *, &, !, %, or @ need quoting.

Anchors and Aliases — YAML anchors (&name) and aliases (*name) let you reuse data, reducing duplication. However, they are fully expanded during JSON conversion, potentially increasing file size. Deeply nested or circular aliases can cause infinite loops in naive parsers. Merge keys (<<: *base) allow inheriting mappings but are not part of the official YAML 1.2 spec and may not be supported by all parsers. Always test anchor-heavy YAML with your specific yaml parser.

# YAML anchors and aliases

# Define an anchor with &
defaults: &default_settings
  adapter: postgres
  host: localhost
  port: 5432

# Reuse with alias *
development:
  database:
    <<: *default_settings     # Merge key: inherits all defaults
    database: myapp_dev

production:
  database:
    <<: *default_settings     # Same defaults
    database: myapp_prod
    host: db.production.com   # Override specific values

# After JSON conversion (anchors fully expanded):
# {
#   "defaults": { "adapter": "postgres", "host": "localhost", "port": 5432 },
#   "development": {
#     "database": {
#       "adapter": "postgres", "host": "localhost",
#       "port": 5432, "database": "myapp_dev"
#     }
#   },
#   "production": {
#     "database": {
#       "adapter": "postgres", "host": "db.production.com",
#       "port": 5432, "database": "myapp_prod"
#     }
#   }
# }

Number and Date Interpretation — Unquoted values like 3.14 become floats, 42 becomes an integer, 0o17 becomes an octal number (15), 0x1F becomes hex (31), and 2024-01-15 may become a date object. If you intend these as strings, quote them. Version numbers like 1.0 are particularly problematic as they become the float 1 instead of the string "1.0".

YAML Best Practices

Follow these best practices to write clean, maintainable YAML that converts to JSON without surprises:

Consistent indentation — Use 2 spaces for indentation throughout your YAML files. This matches the conventions used by Kubernetes, Docker Compose, and most cloud-native tools. Never mix different indentation levels in the same file. Configure your editor's .editorconfig or formatting settings to enforce this automatically.

Quote strings defensively — When in doubt, quote your strings. Always use quotes for values that look like booleans ("yes", "no", "on", "off"), numbers ("1.0", "3.14"), null ("null", "~"), and date-like strings ("2024-01-15"). Prefer double quotes (") for consistency, as they support escape sequences.

Avoid the boolean trap — Be especially careful with country codes (NO, YES), toggle values (on, off), and short answers (y, n). In a yaml to json converter, these silently become true or false unless quoted. Use a linter to catch these issues automatically.

Schema validation — Validate your YAML against a JSON Schema to catch structural errors early. Tools like ajv (JavaScript), jsonschema (Python), and kubeval (Kubernetes) can validate the data after conversion to JSON. For YAML-specific validation, use a yaml validator that checks both syntax and schema compliance.

Lint with yamllint — Install yamllint and run it in your CI/CD pipeline. It checks for common issues: trailing whitespace, inconsistent indentation, missing document start markers, truthy values, and line length. A .yamllint.yml configuration file lets you customize rules for your project. Example: yamllint -d "{extends: default, rules: {line-length: {max: 120}}}" .

# .yamllint.yml configuration example
---
extends: default

rules:
  line-length:
    max: 120
    allow-non-breakable-words: true
  indentation:
    spaces: 2
    indent-sequences: true
  comments:
    min-spaces-from-content: 1
  truthy:
    check-keys: true
    allowed-values: ['true', 'false']
  document-start:
    present: true
  trailing-spaces: enable
  new-line-at-end-of-file: enable

# Run yamllint:
# yamllint .
# yamllint config.yaml
# yamllint -d "{extends: default}" config.yaml

Use comments wisely — One of YAML's biggest advantages over JSON is comment support. Document non-obvious configuration choices, include links to documentation, and explain magic numbers. Remember that comments are lost during yaml to json conversion, so critical information should also be in external documentation.

Frequently Asked Questions

What is the difference between YAML and JSON?

YAML and JSON are both data serialization formats, but they differ in several key ways. YAML uses indentation-based syntax with no brackets or braces, supports comments with #, and offers advanced features like anchors, aliases, and multi-line strings. JSON uses bracket/brace delimiters, has no comment support, and is limited to strings, numbers, booleans, null, arrays, and objects. YAML is more human-readable and preferred for configuration files, while JSON is more widely supported in APIs and programming languages. YAML is technically a superset of JSON, meaning every valid JSON document is also valid YAML.

How do I convert YAML to JSON?

You can convert YAML to JSON using online tools, command-line utilities, or programming libraries. Online: use a yaml to json online converter tool. CLI: install yq and run "yq -o=json file.yaml" or use a Python one-liner "python3 -c 'import sys,yaml,json; json.dump(yaml.safe_load(sys.stdin),sys.stdout,indent=2)' < file.yaml". Programmatically: in JavaScript use js-yaml with JSON.stringify, in Python use PyYAML with json.dumps, in Go use gopkg.in/yaml.v3 with encoding/json. All methods parse the YAML into native data structures and then serialize to JSON.

When should I use YAML vs JSON?

Use YAML for configuration files that humans edit frequently (Kubernetes manifests, Docker Compose, CI/CD pipelines, Ansible playbooks) because its clean syntax, comment support, and multiline strings improve readability. Use JSON for API responses, data exchange between services, browser-based applications, and any context where parsing speed matters or where the data is primarily machine-generated and machine-consumed. Many projects use both: YAML for configuration and JSON for API communication. If you need to switch between formats, a yaml to json converter makes it seamless.

Mastering yaml to json conversion and understanding YAML syntax is essential for modern DevOps and software development. From Kubernetes manifests to CI/CD pipelines, YAML is everywhere in the cloud-native ecosystem. By understanding how the yaml parser works, avoiding common pitfalls like the boolean trap and tab characters, and following best practices for quoting and validation, you can write robust YAML configurations that convert cleanly to JSON every time. Use our free yaml to json online tool and yaml validator to streamline your workflow.

Convert YAML to JSON and JSON to YAML instantly with our free online tool.

𝕏 Twitterin LinkedIn
È stato utile?

Resta aggiornato

Ricevi consigli dev e nuovi strumenti ogni settimana.

Niente spam. Cancella quando vuoi.

Prova questi strumenti correlati

Y{}JSON ↔ YAML ConverterYMLYAML Validator & Formatter{ }JSON Formatter🔄YAML ↔ JSON Converter

Articoli correlati

JSON vs YAML vs TOML: Quale formato di configurazione usare?

Confronta i formati di configurazione JSON, YAML e TOML.

Sintassi YAML e validazione: Errori comuni e soluzioni

Padroneggia la sintassi YAML: regole di indentazione, errori di parsing, tipi di dati e best practice.

YAML Ancore, alias e chiavi di merge

Padroneggia i principi DRY di YAML con ancore (&), alias (*) e chiavi di merge (<<). Riduci la duplicazione in Docker Compose e CI/CD.

Guida al Convertitore JSON-YAML Online: Sintassi, Strumenti e Best Practices

Guida completa alla conversione JSON-YAML. Sintassi, js-yaml, PyYAML, yq CLI, Kubernetes, Docker Compose, insidie YAML e sicurezza.