📖 2 min read (~ 300 words).

The JSON bridge

Converting

j, err := codec.ToJSON([]byte("a: 1\nb: [x, y]\n"))
// {"a": 1, "b": ["x", "y"]}

FromJSON goes the other way. Both are re-exported from the root package, where they take no options; codec.ToJSON takes parser options.

ToJSON walks the document and writes JSON as it reaches each node. Nothing is decoded into a Go value on the way, so a type Go cannot hold does not stop the conversion — and a document too large to model as Go values still converts.

What it refuses

JSON cannot express everything YAML can, and ToJSON reports rather than guesses:

[3:4] JSON has no number for .inf
   1 | a: 1
   2 | b: [x, y]
>  3 | c: .inf
          ^
[1:3] a sequence cannot be a JSON key
>  1 | ? [a,b]
         ^
   2 | : 1

The errors carry a position, so they print like any other — see Errors.

A non-string scalar key is stringified, which can produce a duplicate JSON name: '1.0': 1 and !!float 1: 2 are two YAML keys and one JSON name. parser.WithJSONCompatible reports that pair as ErrNotJSON rather than letting it through.

Go values from a tree

codec.NodeToValue fills a Go value from a node you already have, and ValueToNode builds a subtree from a Go value. To read a source straight to any, call yaml.Unmarshal with a *any: the decoder then builds the values as the parser reads the document and builds no tree.

Conformance

ToJSON scores 272 of 274 on the YAML Test Suite, against 371 of 371 through the decoder — see Conformance.