YAML to JSON and back
The task: serve a YAML configuration as JSON, accept JSON back, and reject whatever does not fit.
The document
const src = `# service
name: api
version: 1.10
ports: [80, 443]
base: &base {retries: 3}
prod:
<<: *base
debug: false
empty:
`Full source: docs/examples/conversion/tojson/example_test.go
Convert to JSON
j, err := codec.ToJSON([]byte(src))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(j))Full source: docs/examples/conversion/tojson/example_test.go
{"name":"api","version":1.10,"ports":[80,443],"base":{"retries":3},"prod":{"<<":{"retries":3},"debug":false},"empty":null}Full source: docs/examples/conversion/tojson/example_test.go
ToJSON builds no Go value. It walks the document and writes JSON as it reads:
1.10keeps its text. A decode intofloat64would give1.1.empty:with no value isnull.- The comment is dropped: JSON has none.
- The alias
*basewrites what its anchor wrote. <<is an ordinary key, as YAML 1.2 reads it.
Merge keys
j, err := codec.ToJSON([]byte(src), parser.WithMergeKeys())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(j))Full source: docs/examples/conversion/tojson/example_test.go
{"name":"api","version":1.10,"ports":[80,443],"base":{"retries":3},"prod":{"debug":false,"retries":3},"empty":null}Full source: docs/examples/conversion/tojson/example_test.go
parser.WithMergeKeys makes << merge the mapping it names, and changes
nothing else. ToJSON takes any parser option.
Back to YAML
j := []byte(`{"name":"api","version":1.10,"enabled":"yes","tags":[],"notes":"one\ntwo\n"}`)
y, err := codec.FromJSON(j)
if err != nil {
fmt.Println(err)
return
}
fmt.Print(string(y))Full source: docs/examples/conversion/tojson/example_test.go
name: api
version: 1.10
enabled: "yes"
tags: []
notes: |
one
twoFull source: docs/examples/conversion/tojson/example_test.go
FromJSON keeps the member order and the number’s text. It quotes "yes",
which would read back as a boolean under YAML 1.1, and writes a string over
several lines as a | block.
Accept JSON only
for _, in := range []string{
`{"a": 1, "b": [true, null]}`,
`a: 1`,
`{"a": 1,}`,
`{"a": 1} # note`,
} {
_, err := parser.ParseBytes([]byte(in), parser.WithJSONSyntax())
fmt.Printf("%-18s JSON: %v\n", in, !errors.Is(err, yerrors.ErrNotJSONSyntax))
}Full source: docs/examples/conversion/tojson/example_test.go
{"a": 1, "b": [true, null]} JSON: true
a: 1 JSON: false
{"a": 1,} JSON: false
{"a": 1} # note JSON: falseFull source: docs/examples/conversion/tojson/example_test.go
YAML reads all of these, since JSON is almost all YAML. parser.WithJSONSyntax
checks each token against JSON’s grammar and rejects the document with
errors.ErrNotJSONSyntax at the first one that is not JSON: a bare key, a
trailing comma, a comment. FromJSON reads its input this way.
A value JSON cannot hold
_, err := codec.ToJSON([]byte("timeout: .inf\n"))
fmt.Println(errors.Is(err, yerrors.ErrNotJSON))
fmt.Println(err)Full source: docs/examples/conversion/tojson/example_test.go
true
[1:10] JSON has no number for .inf
> 1 | timeout: .inf
^Full source: docs/examples/conversion/tojson/example_test.go
JSON has no infinity, NaN or collection key. ToJSON returns an error that
matches errors.ErrNotJSON, with the position and the source around it.
Two keys YAML distinguishes can write one JSON member name:
_, err := codec.ToJSON([]byte("1: a\n\"1\": b\n"))
fmt.Println(err)Full source: docs/examples/conversion/tojson/example_test.go
[2:1] two keys write the JSON member "1", first defined at [1:1]
1 | 1: a
> 2 | "1": b
^Full source: docs/examples/conversion/tojson/example_test.go
The integer 1 and the string "1" are two keys in YAML and one member "1"
in JSON. ToJSON rejects the pair, at the second key.
Variations
- Several documents.
ToJSONconverts the first document of a stream, and still returns an error if a later one cannot be converted. - Tokens instead of one buffer. See JSON tokens as they arrive.
- The full list of what converts. See The JSON bridge.