YAML ⇄ JSON Converter — Go source
Convert YAML to JSON and back, both directions in one tool — swap carries the result straight into the input. Anchors and merge keys resolve on the way in; JSON emits canonical 2-space YAML on the way out.
This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package yamljsonconverter is the Go twin of CosmoDev's src/lib/yaml-json.ts
// (dual source: the web lib wraps the `yaml` npm package in TypeScript, the
// CLI lib pairs gopkg.in/yaml.v3 with encoding/json in Go — kept in lock-step
// so both produce equivalent output). Pure + deterministic, never panics. The
// table-driven tests in yaml-json-converter_test.go share vectors with
// src/lib/yaml-json.test.ts so the two implementations are held to the same
// contract.
//
// Contract pinned by the TS lib: YAML anchors and << merge keys are RESOLVED
// into plain JSON; JSON→YAML emits 2-space canonical YAML with no wrapping;
// empty input yields empty output in both directions; unquoted YAML dates
// (like 2024-01-15) stay strings — neither parser opts into a timestamp
// schema. Strings that would otherwise parse as numbers or booleans stay
// quoted in the YAML output.
//
// Document key order is the hard requirement: Go maps lose insertion order on
// both sides, so YamlToJson walks the yaml.Node tree in document order into
// an ordered jsonNode tree (NOT map[string]any), and JsonToYaml walks the
// JSON bytes with a json.Decoder Token() stream into the same ordered shape
// before emitting canonical YAML.
package yamljsonconverter
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"gopkg.in/yaml.v3"
)
// ConvertResult mirrors the TS ConvertResult union: success carries the
// converted text in Output with a nil Error; failure carries an empty Output
// and the parser's error.
type ConvertResult struct {
Output string
Error error
}
// YamlToJson parses a YAML document and renders it as pretty JSON (2-space
// indent, HTML characters left unescaped — JSON.stringify semantics). Empty
// or whitespace-only input yields empty output with no error, matching the TS
// twin. Anchors resolve through aliases and << merge keys expand (explicit
// keys win over merged ones, earlier merge sources win over later ones) so
// the emitted JSON is plain. Document key order is preserved.
func YamlToJson(raw string) ConvertResult {
text := strings.TrimSpace(raw)
if text == "" {
return ConvertResult{}
}
var doc yaml.Node
if err := yaml.Unmarshal([]byte(text), &doc); err != nil {
return ConvertResult{Error: err}
}
root, err := nodeToJSON(&doc, nil)
if err != nil {
return ConvertResult{Error: err}
}
var compact bytes.Buffer
if err := emitJSON(&compact, root); err != nil {
return ConvertResult{Error: err}
}
// json.Indent reformats the compact text to JSON.stringify(v, null, 2)
// without escaping HTML or adding a trailing newline.
var pretty bytes.Buffer
if err := json.Indent(&pretty, compact.Bytes(), "", " "); err != nil {
return ConvertResult{Error: err}
}
return ConvertResult{Output: pretty.String()}
}
// JsonToYaml parses a JSON document and renders it as canonical YAML
// (2-space block indent, no line wrapping — the TS stringify options
// { indent: 2, lineWidth: 0 }). Empty or whitespace-only input yields empty
// output with no error. Object key order is preserved; strings that would
// otherwise resolve as null/bool/number stay double-quoted (the npm yaml
// default is double quotes).
func JsonToYaml(raw string) ConvertResult {
text := strings.TrimSpace(raw)
if text == "" {
return ConvertResult{}
}
root, err := parseOrderedJSON(text)
if err != nil {
return ConvertResult{Error: err}
}
var buf bytes.Buffer
switch root.kind {
case jkObject:
if len(root.members) == 0 {
buf.WriteString("{}")
} else {
writeBlockMap(&buf, root.members, 0)
}
case jkSequence:
if len(root.items) == 0 {
buf.WriteString("[]")
} else {
writeBlockSeq(&buf, root.items, 0)
}
default:
buf.WriteString(yamlScalarText(root))
}
out := buf.String()
// npm yaml stringify always terminates the document with one newline.
if !strings.HasSuffix(out, "\n") {
out += "\n"
}
return ConvertResult{Output: out}
}
// ---------------------------------------------------------------------------
// Ordered value tree — the JSON-side representation that remembers key order
// for both conversion directions.
// ---------------------------------------------------------------------------
type jsonKind int
const (
jkNull jsonKind = iota
jkBool
jkNumber
jkString
jkObject
jkSequence
)
type jsonMember struct {
key string
value *jsonNode
}
// jsonNode is a JSON value that remembers document order; map[string]any
// cannot, and encoding/json's default unmarshal would silently sort keys.
type jsonNode struct {
kind jsonKind
str string
numText string // rendered JSON number text (shortest round-trip form)
boolean bool
members []jsonMember
items []*jsonNode
}
// containsNode reports whether target is on the current traversal path —
// the cycle guard that keeps circular aliases/merges from hanging the walk.
func containsNode(path []*yaml.Node, target *yaml.Node) bool {
for _, p := range path {
if p == target {
return true
}
}
return false
}
// ---------------------------------------------------------------------------
// YAML → ordered JSON tree
// ---------------------------------------------------------------------------
// nodeToJSON converts a yaml.Node subtree into the ordered jsonNode tree.
// path holds the nodes on the current DFS route for cycle detection.
func nodeToJSON(n *yaml.Node, path []*yaml.Node) (*jsonNode, error) {
if n == nil {
return &jsonNode{kind: jkNull}, nil
}
switch n.Kind {
case yaml.DocumentNode:
if len(n.Content) == 0 {
return &jsonNode{kind: jkNull}, nil // bare "---" parses to null
}
return nodeToJSON(n.Content[0], path)
case yaml.AliasNode:
if n.Alias == nil {
return nil, fmt.Errorf("yaml: unresolved alias")
}
return nodeToJSON(n.Alias, path)
case yaml.MappingNode:
if containsNode(path, n) {
return nil, fmt.Errorf("yaml: circular reference through anchors")
}
return mappingToJSON(n, append(path, n))
case yaml.SequenceNode:
if containsNode(path, n) {
return nil, fmt.Errorf("yaml: circular reference through anchors")
}
path = append(path, n)
out := &jsonNode{kind: jkSequence}
for _, c := range n.Content {
item, err := nodeToJSON(c, path)
if err != nil {
return nil, err
}
out.items = append(out.items, item)
}
return out, nil
case yaml.ScalarNode:
return scalarToJSON(n)
default:
return nil, fmt.Errorf("yaml: unsupported node kind %d", n.Kind)
}
}
// mappingToJSON walks a mapping's key/value pairs in document order, expanding
// merge keys in place. Explicit keys override merged values at the merged
// key's position; a later merge source never clobbers an earlier one.
func mappingToJSON(n *yaml.Node, path []*yaml.Node) (*jsonNode, error) {
out := &jsonNode{kind: jkObject}
index := map[string]int{} // key → position in out.members
for i := 0; i+1 < len(n.Content); i += 2 {
kn, vn := n.Content[i], n.Content[i+1]
if isMergeKey(kn) {
sources, err := mergeSources(vn, path)
if err != nil {
return nil, err
}
for _, src := range sources {
flat, err := mappingToJSON(src, append(path, src))
if err != nil {
return nil, err
}
for _, m := range flat.members {
if _, ok := index[m.key]; !ok {
index[m.key] = len(out.members)
out.members = append(out.members, m)
}
}
}
continue
}
key, err := keyText(kn)
if err != nil {
return nil, err
}
val, err := nodeToJSON(vn, path)
if err != nil {
return nil, err
}
if idx, ok := index[key]; ok {
out.members[idx].value = val // explicit key overrides merged value in place
} else {
index[key] = len(out.members)
out.members = append(out.members, jsonMember{key: key, value: val})
}
}
return out, nil
}
// isMergeKey reports whether kn is the YAML merge key. yaml.v3 resolves a
// plain "<<" to the !!merge tag; quoted "<<" keeps !!str and stays a plain
// key — exactly the npm yaml semantics the TS twin relies on.
func isMergeKey(kn *yaml.Node) bool {
return kn.Kind == yaml.ScalarNode && kn.Tag == "!!merge"
}
// mergeSources dereferences a merge value into the list of mappings to merge,
// in precedence order: a mapping, an alias, or a sequence of those. A null
// merge value merges nothing.
func mergeSources(vn *yaml.Node, path []*yaml.Node) ([]*yaml.Node, error) {
deref := func(x *yaml.Node) (*yaml.Node, error) {
if x.Kind == yaml.AliasNode {
if x.Alias == nil {
return nil, fmt.Errorf("yaml: unresolved alias in merge key")
}
x = x.Alias
}
return x, nil
}
appendSource := func(x *yaml.Node) ([]*yaml.Node, error) {
x, err := deref(x)
if err != nil {
return nil, err
}
if x.Kind != yaml.MappingNode {
return nil, fmt.Errorf("yaml: merge sources must be mappings")
}
if containsNode(path, x) {
return nil, fmt.Errorf("yaml: circular reference through merge key")
}
return []*yaml.Node{x}, nil
}
switch vn.Kind {
case yaml.ScalarNode:
if vn.Tag == "!!null" {
return nil, nil
}
return nil, fmt.Errorf("yaml: merge value must be a mapping, sequence, or null")
case yaml.AliasNode, yaml.MappingNode:
return appendSource(vn)
case yaml.SequenceNode:
var out []*yaml.Node
for _, c := range vn.Content {
src, err := appendSource(c)
if err != nil {
return nil, err
}
out = append(out, src[0])
}
return out, nil
default:
return nil, fmt.Errorf("yaml: merge value must be a mapping, sequence, or null")
}
}
// scalarToJSON resolves a YAML scalar to its JSON value. yaml.v3 has already
// tagged the node (plain scalars resolve per the core schema; quoted scalars
// are !!str), so decoding into interface{} yields exactly what npm yaml's
// parser would — except !!timestamp, which yaml.v3 decodes to time.Time while
// the npm yaml default schema keeps dates as strings; the original literal is
// restored so both twins agree.
func scalarToJSON(n *yaml.Node) (*jsonNode, error) {
if n.Tag == "!!null" {
return &jsonNode{kind: jkNull}, nil
}
var v any
if err := n.Decode(&v); err != nil {
return nil, err
}
if _, ok := v.(time.Time); ok {
return &jsonNode{kind: jkString, str: n.Value}, nil
}
switch x := v.(type) {
case string:
return &jsonNode{kind: jkString, str: x}, nil
case bool:
return &jsonNode{kind: jkBool, boolean: x}, nil
case int:
return &jsonNode{kind: jkNumber, numText: strconv.FormatInt(int64(x), 10)}, nil
case int64:
return &jsonNode{kind: jkNumber, numText: strconv.FormatInt(x, 10)}, nil
case uint64:
return &jsonNode{kind: jkNumber, numText: strconv.FormatUint(x, 10)}, nil
case float64:
return &jsonNode{kind: jkNumber, numText: jsonNumberText(x)}, nil
case []byte: // !!binary — base64 text, the closest JSON form
return &jsonNode{kind: jkString, str: string(x)}, nil
default:
return nil, fmt.Errorf("yaml: unsupported scalar tag %s", n.Tag)
}
}
// keyText renders a mapping key as its JSON object key string (TS implicitly
// does String(key) inside JSON.stringify).
func keyText(kn *yaml.Node) (string, error) {
if kn.Kind != yaml.ScalarNode {
return "", fmt.Errorf("yaml: mapping keys must be scalars")
}
v, err := scalarToJSON(kn)
if err != nil {
return "", err
}
switch v.kind {
case jkString:
return v.str, nil
case jkNull:
return "null", nil
case jkBool:
return strconv.FormatBool(v.boolean), nil
case jkNumber:
return numberKeyText(v.numText), nil
default:
return "", fmt.Errorf("yaml: unsupported mapping key")
}
}
// numberKeyText converts a JSON number literal to its JS String(key) form.
func numberKeyText(numText string) string {
f, err := strconv.ParseFloat(numText, 64)
if err != nil {
return numText
}
if math.IsInf(f, 1) {
return "Infinity"
}
if math.IsInf(f, -1) {
return "-Infinity"
}
if math.IsNaN(f) {
return "NaN"
}
return strconv.FormatFloat(f, 'g', -1, 64)
}
// ---------------------------------------------------------------------------
// JSON output writer — JSON.stringify semantics (2-space via json.Indent,
// no HTML escaping, null for NaN/Infinity).
// ---------------------------------------------------------------------------
// emitJSON writes n as compact JSON without HTML escaping.
func emitJSON(buf *bytes.Buffer, n *jsonNode) error {
switch n.kind {
case jkNull:
buf.WriteString("null")
case jkBool:
buf.WriteString(strconv.FormatBool(n.boolean))
case jkNumber:
buf.WriteString(n.numText)
case jkString:
buf.Write(appendJSONString(nil, n.str))
case jkObject:
buf.WriteByte('{')
for i, m := range n.members {
if i > 0 {
buf.WriteByte(',')
}
buf.Write(appendJSONString(nil, m.key))
buf.WriteByte(':')
if err := emitJSON(buf, m.value); err != nil {
return err
}
}
buf.WriteByte('}')
case jkSequence:
buf.WriteByte('[')
for i, item := range n.items {
if i > 0 {
buf.WriteByte(',')
}
if err := emitJSON(buf, item); err != nil {
return err
}
}
buf.WriteByte(']')
}
return nil
}
// appendJSONString escapes s as a JSON string literal the way encoding/json
// with SetEscapeHTML(false) does (JS JSON.stringify-compatible: no HTML
// escaping; control chars and lone surrogates handled; U+2028/U+2029 escaped
// as encoding/json always does).
func appendJSONString(b []byte, s string) []byte {
b = append(b, '"')
for i := 0; i < len(s); {
c := s[i]
if c < utf8.RuneSelf {
switch c {
case '"':
b = append(b, '\\', '"')
case '\\':
b = append(b, '\\', '\\')
case '\b':
b = append(b, '\\', 'b')
case '\f':
b = append(b, '\\', 'f')
case '\n':
b = append(b, '\\', 'n')
case '\r':
b = append(b, '\\', 'r')
case '\t':
b = append(b, '\\', 't')
default:
if c < 0x20 {
b = append(b, '\\', 'u', '0', '0', "0123456789abcdef"[c>>4], "0123456789abcdef"[c&0xF])
} else {
b = append(b, c)
}
}
i++
continue
}
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
b = append(b, `�`...)
i++
continue
}
if r == 0x2028 || r == 0x2029 {
b = append(b, '\\', 'u', '2', '0', '2', byte('8'+r-0x2028))
i += size
continue
}
b = append(b, s[i:i+size]...)
i += size
}
return append(b, '"')
}
// jsonNumberText renders f the way JSON.stringify does: shortest round-trip
// form, with null for NaN/Infinity (JSON.stringify(NaN) === 'null').
func jsonNumberText(f float64) string {
if math.IsNaN(f) || math.IsInf(f, 0) {
return "null"
}
b, err := json.Marshal(f)
if err != nil {
return "null"
}
return string(b)
}
// ---------------------------------------------------------------------------
// JSON input parser — token stream so object key order survives.
// ---------------------------------------------------------------------------
// parseOrderedJSON parses s into the ordered jsonNode tree, rejecting
// trailing data the way JSON.parse does.
func parseOrderedJSON(s string) (*jsonNode, error) {
dec := json.NewDecoder(strings.NewReader(s))
dec.UseNumber() // numbers as raw literals; float64 would miss json.Number
root, err := decodeJSONNode(dec)
if err != nil {
return nil, err
}
if _, err := dec.Token(); err == io.EOF {
return root, nil
} else if err != nil {
return nil, err
}
return nil, fmt.Errorf("invalid JSON: unexpected data after top-level value")
}
// decodeJSONNode reads the next token and decodes the full value that starts
// with it, preserving object key order.
func decodeJSONNode(dec *json.Decoder) (*jsonNode, error) {
tok, err := dec.Token()
if err != nil {
return nil, err
}
switch t := tok.(type) {
case json.Delim:
switch t {
case '{':
out := &jsonNode{kind: jkObject}
for dec.More() {
keyTok, err := dec.Token()
if err != nil {
return nil, err
}
key, ok := keyTok.(string)
if !ok {
return nil, fmt.Errorf("invalid JSON: non-string object key")
}
val, err := decodeJSONNode(dec)
if err != nil {
return nil, err
}
out.members = append(out.members, jsonMember{key: key, value: val})
}
if _, err := dec.Token(); err != nil { // consume '}'
return nil, err
}
return out, nil
case '[':
out := &jsonNode{kind: jkSequence}
for dec.More() {
item, err := decodeJSONNode(dec)
if err != nil {
return nil, err
}
out.items = append(out.items, item)
}
if _, err := dec.Token(); err != nil { // consume ']'
return nil, err
}
return out, nil
default:
return nil, fmt.Errorf("invalid JSON: unexpected delimiter %v", t)
}
case string:
return &jsonNode{kind: jkString, str: t}, nil
case json.Number:
return &jsonNode{kind: jkNumber, numText: normalizeNumber(t.String())}, nil
case bool:
return &jsonNode{kind: jkBool, boolean: t}, nil
case nil:
return &jsonNode{kind: jkNull}, nil
default:
return nil, fmt.Errorf("invalid JSON: unexpected token %v", tok)
}
}
// normalizeNumber re-renders a JSON number literal in the shortest form
// JSON.stringify would print (JSON.parse feeds everything through a double).
// Literals out of float range become Infinity on the JS side, which
// stringify renders as null.
func normalizeNumber(raw string) string {
f, err := strconv.ParseFloat(raw, 64)
if err != nil {
if math.IsInf(f, 0) || math.IsNaN(f) {
return "null"
}
return raw
}
return jsonNumberText(f)
}
// ---------------------------------------------------------------------------
// YAML output writer — canonical 2-space block style (npm yaml stringify
// { indent: 2, lineWidth: 0 }).
// ---------------------------------------------------------------------------
// writeBlockMap writes each member on its own line at the given indent.
func writeBlockMap(buf *bytes.Buffer, members []jsonMember, indent int) {
for _, m := range members {
writeIndent(buf, indent)
writeKeyValue(buf, yamlEncodeString(m.key), m.value, indent)
}
}
// writeBlockSeq writes each item as "- ..." at the given indent.
func writeBlockSeq(buf *bytes.Buffer, items []*jsonNode, indent int) {
for _, item := range items {
writeIndent(buf, indent)
buf.WriteByte('-')
writeItemAfterDash(buf, item, indent)
}
}
// writeKeyValue writes `key:` plus the value. Scalars continue on the line;
// non-empty collections open a block indented two more.
func writeKeyValue(buf *bytes.Buffer, key string, val *jsonNode, entryIndent int) {
buf.WriteString(key)
buf.WriteByte(':')
switch val.kind {
case jkObject:
if len(val.members) == 0 {
buf.WriteString(" {}\n")
return
}
buf.WriteByte('\n')
writeBlockMap(buf, val.members, entryIndent+2)
case jkSequence:
if len(val.items) == 0 {
buf.WriteString(" []\n")
return
}
buf.WriteByte('\n')
writeBlockSeq(buf, val.items, entryIndent+2)
default:
buf.WriteByte(' ')
buf.WriteString(yamlScalarText(val))
buf.WriteByte('\n')
}
}
// writeItemAfterDash writes a sequence item with the cursor sitting right
// after the dash. Non-empty collections start inline ("- x: 1" / "- - 1")
// with continuation lines aligned two columns past the dash.
func writeItemAfterDash(buf *bytes.Buffer, item *jsonNode, dashIndent int) {
switch item.kind {
case jkObject:
if len(item.members) == 0 {
buf.WriteString(" {}\n")
return
}
buf.WriteByte(' ')
m := item.members[0]
writeKeyValue(buf, yamlEncodeString(m.key), m.value, dashIndent+2)
writeBlockMap(buf, item.members[1:], dashIndent+2)
case jkSequence:
if len(item.items) == 0 {
buf.WriteString(" []\n")
return
}
buf.WriteString(" -")
writeItemAfterDash(buf, item.items[0], dashIndent+2)
writeBlockSeq(buf, item.items[1:], dashIndent+2)
default:
buf.WriteByte(' ')
buf.WriteString(yamlScalarText(item))
buf.WriteByte('\n')
}
}
// writeIndent writes exactly indent spaces (indent is a space count; child
// blocks are always entryIndent+2).
func writeIndent(buf *bytes.Buffer, indent int) {
buf.WriteString(strings.Repeat(" ", indent))
}
// yamlScalarText renders a JSON value as a YAML scalar token.
func yamlScalarText(n *jsonNode) string {
switch n.kind {
case jkNull:
return "null"
case jkBool:
return strconv.FormatBool(n.boolean)
case jkNumber:
return n.numText
case jkString:
return yamlEncodeString(n.str)
default:
return "null" // unreachable for scalars; never panic
}
}
// yamlEncodeString quotes s when a plain scalar would change its meaning:
// core-schema nulls/bools/numbers, document markers, indicator leads, comment
// and mapping colon sequences, or control characters. The npm yaml default
// (singleQuote: false) double-quotes, and JSON escaping is valid YAML
// double-quoted escaping, so multi-line strings round-trip as quoted too.
func yamlEncodeString(s string) string {
if plainSafe(s) {
return s
}
return string(appendJSONString(nil, s))
}
// coreSchemaNonString reports whether s resolves to a YAML 1.2 core-schema
// null, bool, or number — the words a plain scalar may not carry if it must
// stay a string.
var (
coreWords = regexp.MustCompile(`^(null|Null|NULL|~|true|True|TRUE|false|False|FALSE|\.inf|\.Inf|\.INF|[+-]\.inf|[+-]\.Inf|[+-]\.INF|\.nan|\.NaN|\.NAN)$`)
coreIntLike = regexp.MustCompile(`^[-+]?(0x[0-9a-fA-F]+|0o[0-7]+|[0-9]+)$`)
coreFloatLike = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`)
)
func coreSchemaNonString(s string) bool {
if coreWords.MatchString(s) || coreFloatLike.MatchString(s) {
return true
}
return coreIntLike.MatchString(s)
}
// plainSafe reports whether s can be emitted unquoted in block context
// without changing its meaning on re-parse.
func plainSafe(s string) bool {
if s == "" || coreSchemaNonString(s) {
return false
}
if strings.HasPrefix(s, "---") || strings.HasPrefix(s, "...") {
return false // document markers
}
runes := []rune(s)
first, last := runes[0], runes[len(runes)-1]
if first == ' ' || first == '\t' || last == ' ' || last == '\t' {
return false
}
if first != '-' && strings.ContainsRune(",[]{}#&*!|>'\"%@`", first) {
return false
}
if (first == '-' || first == '?' || first == ':') && (len(runes) == 1 || runes[1] == ' ' || runes[1] == '\t') {
return false
}
for i, r := range runes {
if r < 0x20 || r == 0x7f {
return false
}
if r == ':' && (i == len(runes)-1 || runes[i+1] == ' ' || runes[i+1] == '\t') {
return false
}
if r == '#' && i > 0 && runes[i-1] == ' ' {
return false
}
}
return true
}
Also available in 1 other language
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in several languages — the same contract, ported. Compare all languages side by side →