Blog
Wild & Free Tools

Convert YAML to JSON in Go — Complete Guide with Examples

Last updated: February 2026 6 min read
Quick Answer

Table of Contents

  1. Install gopkg.in/yaml.v3
  2. Parse YAML into a Struct
  3. Parse Dynamic YAML into a Map
  4. CLI Tool — Read YAML File, Write JSON
  5. Quick Conversion Without Code
  6. Frequently Asked Questions

Converting YAML to JSON in Go takes two steps: parse the YAML with a YAML library, then marshal the result to JSON with Go's standard encoding/json package. Go's standard library does not include a YAML parser, so you need one external dependency: gopkg.in/yaml.v3.

This guide covers both common patterns — parsing into a typed struct when you know the schema, and parsing into a generic map when the YAML structure is dynamic. It also includes a complete CLI tool that reads a YAML file and writes JSON output.

Install gopkg.in/yaml.v3

Add the YAML package to your Go module:

go get gopkg.in/yaml.v3

This is the most widely used YAML library for Go. It supports YAML 1.2, including anchors, aliases, multiline strings, and all standard YAML types. The v3 version is current; avoid v2 for new projects.

Import it alongside the standard JSON package:

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

Approach 1 — Parse YAML into a Typed Struct

When you know the YAML schema, define a struct and unmarshal directly into it. This is the idiomatic Go approach.

package main

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

type Config struct {
    Server struct {
        Host string `yaml:"host"`
        Port int    `yaml:"port"`
    } `yaml:"server"`
    Debug bool `yaml:"debug"`
}

func main() {
    yamlData := []byte(`
server:
  host: localhost
  port: 8080
debug: false
`)

    var cfg Config
    if err := yaml.Unmarshal(yamlData, &cfg); err != nil {
        panic(err)
    }

    jsonData, err := json.MarshalIndent(cfg, "", "  ")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(jsonData))
}

Output:

{
  "Server": {
    "Host": "localhost",
    "Port": 8080
  },
  "Debug": false
}

Note: json.MarshalIndent uses the struct field names (capitalized) unless you add json:"..." tags. Add JSON tags to control output key names:

Server struct {
    Host string `yaml:"host" json:"host"`
    Port int    `yaml:"port" json:"port"`
} `yaml:"server" json:"server"`
Sell Custom Apparel — We Handle Printing & Free Shipping

Approach 2 — Parse Dynamic YAML into a Map

When the YAML structure is not known at compile time, unmarshal into map[string]interface{}. There is a catch: gopkg.in/yaml.v3 unmarshals map keys as interface{}, not string, which causes encoding/json to fail with "json: unsupported type: map[interface{}]interface{}".

The fix is a recursive type conversion function:

package main

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

func convertKeys(v interface{}) interface{} {
    switch v := v.(type) {
    case map[interface{}]interface{}:
        m := make(map[string]interface{})
        for key, val := range v {
            m[fmt.Sprintf("%v", key)] = convertKeys(val)
        }
        return m
    case []interface{}:
        for i, item := range v {
            v[i] = convertKeys(item)
        }
        return v
    default:
        return v
    }
}

func yamlToJSON(yamlBytes []byte) ([]byte, error) {
    var raw interface{}
    if err := yaml.Unmarshal(yamlBytes, &raw); err != nil {
        return nil, err
    }
    converted := convertKeys(raw)
    return json.MarshalIndent(converted, "", "  ")
}

func main() {
    input := []byte(`
name: Alice
roles:
  - admin
  - viewer
settings:
  timeout: 30
`)
    out, err := yamlToJSON(input)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(out))
}

This handles arbitrary YAML structure regardless of depth or key types.

CLI Tool — Convert a YAML File to JSON from the Command Line

A complete Go program that reads a YAML file path from args and prints JSON to stdout:

package main

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

func convertKeys(v interface{}) interface{} {
    switch v := v.(type) {
    case map[interface{}]interface{}:
        m := make(map[string]interface{})
        for k, val := range v {
            m[fmt.Sprintf("%v", k)] = convertKeys(val)
        }
        return m
    case []interface{}:
        for i, item := range v {
            v[i] = convertKeys(item)
        }
        return v
    }
    return v
}

func main() {
    if len(os.Args) < 2 {
        fmt.Fprintln(os.Stderr, "Usage: yaml2json ")
        os.Exit(1)
    }
    data, err := os.ReadFile(os.Args[1])
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    var raw interface{}
    if err := yaml.Unmarshal(data, &raw); err != nil {
        fmt.Fprintln(os.Stderr, "YAML parse error:", err)
        os.Exit(1)
    }
    out, err := json.MarshalIndent(convertKeys(raw), "", "  ")
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println(string(out))
}

Build and run:

go build -o yaml2json main.go
./yaml2json config.yaml > config.json

Quick Conversion Without Writing Go Code

If you need a one-off conversion without writing a program, use the free browser-based YAML to JSON converter. Paste the YAML, click Convert, copy the JSON output. No Go code required, no build step, no dependencies to install.

Use the Go approach when the conversion is part of an application, a pipeline, or needs to run automatically on many files. Use the browser tool for quick manual conversions during development or debugging.

Test YAML to JSON Without Writing Code

Paste your YAML into the browser converter and click Convert. Instant JSON output — useful for testing your Go code's expected output.

Open Free YAML to JSON Converter

Frequently Asked Questions

How do I convert YAML to JSON in Go?

Install gopkg.in/yaml.v3 (go get gopkg.in/yaml.v3). Unmarshal your YAML bytes into an interface{} with yaml.Unmarshal. Run a recursive key-conversion function to convert map[interface{}]interface{} keys to strings. Then marshal the result to JSON with json.MarshalIndent.

Why does Go YAML to JSON fail with "unsupported type: map[interface{}]interface{}"?

gopkg.in/yaml.v3 unmarshals YAML maps with interface{} keys, but encoding/json requires string keys. Fix: write a recursive convertKeys function that walks the data structure and converts all map keys to strings using fmt.Sprintf before calling json.Marshal.

Which Go YAML library should I use?

gopkg.in/yaml.v3 is the current standard. Avoid v2 for new projects. github.com/goccy/go-yaml is a popular alternative with better error messages and JSON tag compatibility. Both support full YAML 1.2.

Is there a Go standard library YAML parser?

No. Go's standard library includes encoding/json and encoding/xml but not YAML. You need an external package. gopkg.in/yaml.v3 is the most commonly used option.

Alicia Grant
Alicia Grant Frontend Engineer

Alicia leads image and PDF tool development at WildandFree, specializing in high-performance client-side browser tools.

More articles by Alicia →
Launch Your Own Clothing Brand — No Inventory, No Risk