Skip to content

How to convert YAML ↔ JSON (and avoid type pitfalls)

Real snippets to convert YAML to JSON (and back). Includes dependencies and notes about implicit types and indentation.

← Developer Zone
Updated: 2026-03-22

Use this article when...

This section is built for speed: one concrete task, multiple stacks, and the minimum context needed not to copy the wrong thing.

Use this after capturing the real payload

Work from the request or response body that actually failed instead of rebuilding JSON from memory.

Pick the language that matches the incident

The useful path here is fast adaptation: choose your stack, then copy only after reading the notes around parsing and formatting.

Validate the result with the tool

Once the snippet runs, inspect the live payload with JSON Formatter or the related tool to confirm the structure is really fixed.

What this article gives you

A short path from incident to implementation: context, language-specific snippets, and the warning signs that usually get skipped.

Languages

13

Related tools

3

Topics

yaml, json, devops, config

Converting YAML ↔ JSON helps you inspect structure and catch mistakes: broken indentation, wrong arrays, or surprising types (true/false, numbers, strings).

Practical rule: if a value must remain a string ("001", "true"), quote it in YAML. For production, validate in CI and review diffs with formatted output.

Dependency snapshot by language

Check this first to see which snippets use built-in/runtime APIs and which ones need external packages before you start copying code.

Bash
External

yaml (npm).

C#
External

YamlDotNet.

Delphi
Check notes

Review the notes for setup details.

Go
External

gopkg.in/yaml.v3.

Java
Check notes

Review the notes for setup details.

JavaScript
External

yaml (npm).

Kotlin
Check notes

Review the notes for setup details.

PHP
External

symfony/yaml (Composer).

Python
External

PyYAML.

Ruby
Built-in

Built-in or runtime API

Rust
Check notes

Review the notes for setup details.

TypeScript
External

yaml (npm).

VB.NET
External

YamlDotNet.

How to use these code examples well

The snippet is only the fast path. The explanation and notes are what keep you from copying the wrong assumption into production.

1. Start with the problem

Make sure the article really matches the issue you are debugging before copying code just because the title looks close.

2. Read the notes

That is where portability limits, dependency requirements, and runtime assumptions usually appear.

3. Validate the output

If the code runs but the bug remains, jump to the related tool and inspect the real payload, token, timestamp, or config.

Code examples by language

Snippets that compile/run, plus short explanations and real-world notes.

Bash

bash
Bash
node --input-type=module -e "import YAML from "yaml"; const y="a: 1\nb: true\nname: Maria\n"; const obj=YAML.parse(y); console.log(JSON.stringify(obj,null,2)); console.log(YAML.stringify(obj));"
Explanation

With Node.js and the yaml package you can convert YAML↔JSON in scripts (great for repos/CI).

Notes
  • Dependency: yaml (npm).
  • Note: YAML may infer types; use quotes to force strings.

C#

csharp
C#
using System;
using System.Text.Json;
using YamlDotNet.Serialization;

var yaml = "a: 1\nb: true\nname: Maria\n";
var deserializer = new DeserializerBuilder().Build();
var obj = deserializer.Deserialize<object>(yaml);
Console.WriteLine(JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true }));
Explanation

YamlDotNet parses YAML into .NET objects, then you serialize to readable JSON using System.Text.Json.

Notes
  • Dependency: YamlDotNet.

Delphi

delphi
Delphi
program YamlFlatToJson;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.JSON,
  System.Classes;

function YamlFlatToJson(const Yaml: string): string;
var
  Lines: TStringList;
  Obj: TJSONObject;
  I: Integer;
  L, K, V: string;
  P: Integer;
  N: Integer;
begin
  Lines := TStringList.Create;
  Obj := TJSONObject.Create;
  try
    Lines.Text := Yaml;
    for I := 0 to Lines.Count - 1 do
    begin
      L := Trim(Lines[I]);
      if (L = '') or L.StartsWith('#') then
        Continue;
      P := L.IndexOf(':');
      if P < 0 then
        Continue;
      K := Trim(L.Substring(0, P));
      V := Trim(L.Substring(P + 1));
      if SameText(V, 'true') then
        Obj.AddPair(K, TJSONBool.Create(True))
      else if SameText(V, 'false') then
        Obj.AddPair(K, TJSONBool.Create(False))
      else if TryStrToInt(V, N) then
        Obj.AddPair(K, TJSONNumber.Create(N))
      else
        Obj.AddPair(K, V);
    end;
    Result := Obj.ToString;
  finally
    Obj.Free;
    Lines.Free;
  end;
end;

begin
  Writeln(YamlFlatToJson('a: 1'#10'b: true'#10'name: Maria'#10));
end.
Explanation

Delphi has no standard YAML library. This snippet converts flat YAML only (key: value) to JSON. For real YAML (nested/arrays/multiline) you need a YAML library.

Notes
  • Limited: no nesting, arrays, or multiline.
  • It treats true/false and integers as types, not strings.
  • Useful only for simple configs and quick debugging.

Go

go
Go
package main

import (
  "encoding/json"
  "fmt"
  "gopkg.in/yaml.v3"
)

func main() {
  y := []byte("a: 1\nb: true\nname: Maria\n")
  var v any
  if err := yaml.Unmarshal(y, &v); err != nil {
    panic(err)
  }
  b, _ := json.MarshalIndent(v, "", "  ")
  fmt.Println(string(b))
}
Explanation

With yaml.v3 you parse YAML and with encoding/json you print formatted JSON.

Notes
  • Dependency: gopkg.in/yaml.v3.
  • Watch inferred types in YAML.

Java

java
Java
import org.yaml.snakeyaml.Yaml;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
  public static void main(String[] args) throws Exception {
    Object obj = new Yaml().load("a: 1\nb: true\nname: Maria\n");
    var mapper = new ObjectMapper();
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
  }
}
Explanation

SnakeYAML parses YAML and Jackson serializes to JSON. A common pattern in Java tooling.

Notes
  • Dependencies: org.yaml:snakeyaml and jackson-databind.

JavaScript

javascript
JavaScript
import YAML from "yaml";

const y = "a: 1\nb: true\nname: Maria\n";
const obj = YAML.parse(y);
console.log(JSON.stringify(obj, null, 2));
Explanation

YAML.parse returns a JS object. JSON.stringify makes it easy to inspect or share.

Notes
  • Dependency: yaml (npm).

Kotlin

kotlin
Kotlin
import org.yaml.snakeyaml.Yaml
import com.fasterxml.jackson.databind.ObjectMapper

fun main() {
  val obj: Any = Yaml().load("a: 1\nb: true\nname: Maria\n")
  val mapper = ObjectMapper()
  println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj))
}
Explanation

Kotlin/JVM can use SnakeYAML + Jackson like Java.

Notes
  • Dependencies: snakeyaml + jackson-databind.

PHP

php
PHP
<?php
use Symfony\Component\Yaml\Yaml;

$y = "a: 1\nb: true\nname: Maria\n";
$data = Yaml::parse($y);
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
Explanation

Symfony Yaml parses YAML into PHP arrays. json_encode outputs readable JSON for debugging.

Notes
  • Dependency: symfony/yaml (Composer).

Python

python
Python
import json
import yaml

y = "a: 1\nb: true\nname: Maria\n"
obj = yaml.safe_load(y)
print(json.dumps(obj, indent=2, ensure_ascii=False))
Explanation

PyYAML safe_load parses YAML without executing dangerous tags. Then you output pretty JSON.

Notes
  • Dependency: PyYAML.

Ruby

ruby
Ruby
require "yaml"
require "json"

y = "a: 1\nb: true\nname: Maria\n"
obj = YAML.safe_load(y, permitted_classes: [], aliases: false)
puts JSON.pretty_generate(obj)
Explanation

Ruby ships with YAML and JSON. safe_load is preferred for untrusted YAML.

Notes
  • Std.

Rust

rust
Rust
use serde_yaml::Value as YamlValue;

fn main() {
  let y = "a: 1\nb: true\nname: Maria\n";
  let v: YamlValue = serde_yaml::from_str(y).unwrap();
  println!("{}", serde_json::to_string_pretty(&v).unwrap());
}
Explanation

serde_yaml parses YAML and serde_json prints formatted JSON. A direct way to convert formats.

Notes
  • Dependencies: serde_yaml + serde_json.

TypeScript

ts
TypeScript
import YAML from "yaml";

const y = "a: 1\nb: true\nname: Maria\n";
const obj = YAML.parse(y) as unknown;
console.log(JSON.stringify(obj, null, 2));
Explanation

In TS, treat YAML.parse as unknown for strictness. Then JSON.stringify with indentation.

Notes
  • Dependency: yaml (npm).

VB.NET

vbnet
VB.NET
Imports System
Imports System.Text.Json
Imports YamlDotNet.Serialization

Module Program
  Sub Main()
    Dim y = "a: 1" & vbLf & "b: true" & vbLf & "name: Maria" & vbLf
    Dim deserializer = New DeserializerBuilder().Build()
    Dim obj = deserializer.Deserialize(Of Object)(y)
    Console.WriteLine(JsonSerializer.Serialize(obj, New JsonSerializerOptions With {.WriteIndented = True}))
  End Sub
End Module
Explanation

YamlDotNet parses YAML and System.Text.Json prints it as indented JSON.

Notes
  • Dependency: YamlDotNet.

Related tools

Use the tool when you need to generate or validate output fast.

Trust and privacy

Copy/paste-friendly by design. Still, treat real production secrets carefully.

  • Prefer synthetic examples when sharing screens or recording.
  • Do not paste real API keys, tokens, or personal data unless you fully trust your environment.
  • If you need ordering, do not use UUID v4 as a sortable id: add createdAt or use sortable ids.