Turn a YAML file into JSON, or JSON into YAML, with oneyaml and the standard library’s encoding/json.
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)) }
{ "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 becomesmap[string]any, a sequence[]any, an integerint, a floatfloat64andnullnil, all of whichencoding/jsonwrites. - Go maps have no order, so both
encoding/jsonandMarshalwrite 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, whichencoding/jsoncan’t write. Values JSON can’t hold, such as.nan, fail atjson.Marshal. - JSON is valid YAML 1.2, so
Unmarshalreads JSON text directly. - For typed data, skip
any:Unmarshalinto your struct andjson.Marshalit.