Recursive AI

Convert YAML to JSON and back

All oneyaml Go recipes

Turn a YAML file into JSON, or JSON into YAML, with oneyaml and the standard library’s encoding/json.

GO
package main
 
import (
	"encoding/json"
	"fmt"
	"log"
 
	oneyaml "oneyaml.dev/go"
)
 
func main() {
	// YAML to JSON: read into any, write with encoding/json.
	var v any
	err := oneyaml.Unmarshal([]byte(`name: web
ports: [80, 443]
tls: true
owner: ~
`), &v)
	if err != nil {
		log.Fatal(err)
	}
	out, err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(out))
 
	// JSON to YAML: JSON is valid YAML 1.2, so read it and write YAML.
	var w any
	if err := oneyaml.Unmarshal([]byte(`{"name": "web", "ports": [80, 443], "env": {"LOG": "info"}}`), &w); err != nil {
		log.Fatal(err)
	}
	y, err := oneyaml.Marshal(w)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(y))
}
Text
{
  "name": "web",
  "owner": null,
  "ports": [
    80,
    443
  ],
  "tls": true
}
env:
  LOG: info
name: web
ports:
  - 80
  - 443

Good to know

  • Read into any: a mapping becomes map[string]any, a sequence []any, an integer int, a float float64 and null nil, all of which encoding/json writes.
  • Go maps have no order, so both encoding/json and Marshal write their keys sorted. To keep the file’s order, read into a struct instead.
  • A mapping with a key that isn’t a string becomes map[any]any, which encoding/json can’t write. Values JSON can’t hold, such as .nan, fail at json.Marshal.
  • JSON is valid YAML 1.2, so Unmarshal reads JSON text directly.
  • For typed data, skip any: Unmarshal into your struct and json.Marshal it.