Convert JSON to YAML in Golang [Complete Guide]

Convert JSON to YAML in Go using the gopkg.in/yaml.v3 package. Unmarshal JSON with Go's built-in encoding/json, then marshal to YAML with yaml.v3. Not sure which format to use? Check our YAML vs JSON comparison. This guide covers complete code examples for Go JSON to YAML conversion, including error handling and struct-based approaches.

Install yaml.v3 Package

Go doesn't have built-in YAML support (unlike JSON, which is in the standard library). Install the most popular YAML package. Prefer a different language? See our Python, Java, or JavaScript guides.

# Install yaml.v3
go get gopkg.in/yaml.v3

# Or add to go.mod
require gopkg.in/yaml.v3 v3.0.1
Note: Use yaml.v3 (not v2) for better YAML 1.2 compliance and improved handling of complex types. This is especially important for Kubernetes and DevOps configurations.

Basic JSON to YAML Conversion

The simplest way to convert JSON to YAML in Golang uses a map[string]interface{}:

package main

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

    "gopkg.in/yaml.v3"
)

func JsonToYaml(jsonData []byte) ([]byte, error) {
    // Unmarshal JSON to map
    var data map[string]interface{}
    if err := json.Unmarshal(jsonData, &data); err != nil {
        return nil, fmt.Errorf("invalid JSON: %w", err)
    }

    // Marshal to YAML
    yamlData, err := yaml.Marshal(data)
    if err != nil {
        return nil, fmt.Errorf("YAML marshal error: %w", err)
    }

    return yamlData, nil
}

func main() {
    jsonStr := `{
        "name": "my-app",
        "version": "1.0.0",
        "config": {
            "port": 8080,
            "debug": true
        }
    }`

    yamlData, err := JsonToYaml([]byte(jsonStr))
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(yamlData))
}

Output:

config:
    debug: true
    port: 8080
name: my-app
version: 1.0.0

Using Structs for Type Safety

For better type safety and control, define Go structs with both JSON and YAML tags:

package main

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

    "gopkg.in/yaml.v3"
)

type Config struct {
    Name    string `json:"name" yaml:"name"`
    Version string `json:"version" yaml:"version"`
    Server  Server `json:"server" yaml:"server"`
}

type Server struct {
    Port    int    `json:"port" yaml:"port"`
    Host    string `json:"host" yaml:"host"`
    Timeout int    `json:"timeout" yaml:"timeout"`
}

func main() {
    jsonStr := `{
        "name": "api-service",
        "version": "2.0.0",
        "server": {
            "port": 3000,
            "host": "localhost",
            "timeout": 30
        }
    }`

    // Unmarshal JSON to struct
    var config Config
    if err := json.Unmarshal([]byte(jsonStr), &config); err != nil {
        log.Fatal(err)
    }

    // Marshal struct to YAML
    yamlData, err := yaml.Marshal(&config)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(yamlData))
}

Output:

name: api-service
version: 2.0.0
server:
    port: 3000
    host: localhost
    timeout: 30

Convert YAML to JSON in Go

Reverse the process to convert YAML to JSON in Golang. For quick one-off conversions, you can also use our online JSON to YAML converter.

func YamlToJson(yamlData []byte) ([]byte, error) {
    // Unmarshal YAML to map
    var data map[string]interface{}
    if err := yaml.Unmarshal(yamlData, &data); err != nil {
        return nil, fmt.Errorf("invalid YAML: %w", err)
    }

    // Marshal to JSON with indentation
    jsonData, err := json.MarshalIndent(data, "", "  ")
    if err != nil {
        return nil, fmt.Errorf("JSON marshal error: %w", err)
    }

    return jsonData, nil
}

func main() {
    yamlStr := `
name: my-app
version: 1.0.0
config:
    port: 8080
    debug: true
`

    jsonData, err := YamlToJson([]byte(yamlStr))
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(jsonData))
}

File-based Conversion

Convert JSON files to YAML files:

package main

import (
    "encoding/json"
    "log"
    "os"

    "gopkg.in/yaml.v3"
)

func ConvertJsonFileToYaml(inputPath, outputPath string) error {
    // Read JSON file
    jsonData, err := os.ReadFile(inputPath)
    if err != nil {
        return err
    }

    // Parse JSON
    var data interface{}
    if err := json.Unmarshal(jsonData, &data); err != nil {
        return err
    }

    // Convert to YAML
    yamlData, err := yaml.Marshal(data)
    if err != nil {
        return err
    }

    // Write YAML file
    return os.WriteFile(outputPath, yamlData, 0644)
}

func main() {
    err := ConvertJsonFileToYaml("config.json", "config.yaml")
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Converted config.json to config.yaml")
}

Error Handling Best Practices

Always handle errors properly in production code:

func SafeJsonToYaml(jsonData []byte) ([]byte, error) {
    if len(jsonData) == 0 {
        return nil, fmt.Errorf("empty JSON input")
    }

    var data interface{}
    if err := json.Unmarshal(jsonData, &data); err != nil {
        var syntaxErr *json.SyntaxError
        if errors.As(err, &syntaxErr) {
            return nil, fmt.Errorf("JSON syntax error at position %d: %w", 
                syntaxErr.Offset, err)
        }
        return nil, fmt.Errorf("JSON parse error: %w", err)
    }

    yamlData, err := yaml.Marshal(data)
    if err != nil {
        return nil, fmt.Errorf("YAML marshal error: %w", err)
    }

    return yamlData, nil
}

Frequently Asked Questions

How do I convert JSON to YAML in Go?

Use encoding/json to unmarshal JSON into a map or struct, then use gopkg.in/yaml.v3 to marshal it to YAML. Install with go get gopkg.in/yaml.v3. The process is: json.Unmarshal(jsonData, &data) then yaml.Marshal(data).

What is the best Go library for YAML?

gopkg.in/yaml.v3 is the most widely used YAML library for Go. It supports YAML 1.2, has good performance, and is actively maintained. For simpler use cases, sigs.k8s.io/yaml is also popular in Kubernetes projects.

Can I convert YAML to JSON in Golang?

Yes, reverse the process: use yaml.Unmarshal to parse YAML, then json.Marshal to convert to JSON. The same data structure can be used for both directions of conversion.

Does Go have built-in YAML support?

No, Go's standard library includes encoding/json for JSON but no YAML package. You need to install a third-party package like gopkg.in/yaml.v3 using go get.

Need to convert JSON to YAML quickly?

Use our free online converter—no Go code required.

Open Converter Tool →