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.
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.
Work from the request or response body that actually failed instead of rebuilding JSON from memory.
The useful path here is fast adaptation: choose your stack, then copy only after reading the notes around parsing and formatting.
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.
13
3
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.
yaml (npm).
YamlDotNet.
Review the notes for setup details.
gopkg.in/yaml.v3.
Review the notes for setup details.
yaml (npm).
Review the notes for setup details.
symfony/yaml (Composer).
PyYAML.
Built-in or runtime API
Review the notes for setup details.
yaml (npm).
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.
Make sure the article really matches the issue you are debugging before copying code just because the title looks close.
That is where portability limits, dependency requirements, and runtime assumptions usually appear.
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
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));"
With Node.js and the yaml package you can convert YAML↔JSON in scripts (great for repos/CI).
- Dependency: yaml (npm).
- Note: YAML may infer types; use quotes to force strings.
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 }));
YamlDotNet parses YAML into .NET objects, then you serialize to readable JSON using System.Text.Json.
- Dependency: YamlDotNet.
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.
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.
- 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
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))
}
With yaml.v3 you parse YAML and with encoding/json you print formatted JSON.
- Dependency: gopkg.in/yaml.v3.
- Watch inferred types in YAML.
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));
}
}
SnakeYAML parses YAML and Jackson serializes to JSON. A common pattern in Java tooling.
- Dependencies: org.yaml:snakeyaml and jackson-databind.
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));
YAML.parse returns a JS object. JSON.stringify makes it easy to inspect or share.
- Dependency: yaml (npm).
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))
}
Kotlin/JVM can use SnakeYAML + Jackson like Java.
- Dependencies: snakeyaml + jackson-databind.
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;
Symfony Yaml parses YAML into PHP arrays. json_encode outputs readable JSON for debugging.
- Dependency: symfony/yaml (Composer).
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))
PyYAML safe_load parses YAML without executing dangerous tags. Then you output pretty JSON.
- Dependency: PyYAML.
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)
Ruby ships with YAML and JSON. safe_load is preferred for untrusted YAML.
- Std.
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());
}
serde_yaml parses YAML and serde_json prints formatted JSON. A direct way to convert formats.
- Dependencies: serde_yaml + serde_json.
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));
In TS, treat YAML.parse as unknown for strictness. Then JSON.stringify with indentation.
- Dependency: yaml (npm).
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
YamlDotNet parses YAML and System.Text.Json prints it as indented JSON.
- 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.