📖 3 min read (~ 700 words).

JSON tokens as they arrive

The task: find one value in a large YAML file, as a JSON pointer, with its line and column, without converting the rest.

The document

const src = `name: api
ports: [80, 443]
db: {host: localhost}
`

Full source: docs/examples/conversion/jsontokens/example_test.go

Range over the tokens

ts := codec.ToJSONTokens([]byte(src))
for tok := range ts.Tokens() {
	// Path and Depth describe the token the loop is on: call them inside the loop.
	fmt.Printf("%-6v %-11q %-10q %d:%d\n", tok.Kind, tok.Value, ts.Path(), tok.At.Line, tok.At.Column)
}
if err := ts.Err(); err != nil {
	fmt.Println(err)
}

Full source: docs/examples/conversion/jsontokens/example_test.go

{      ""          ""         1:1
key    "name"      "/name"    1:1
string "api"       "/name"    1:7
key    "ports"     "/ports"   2:1
[      ""          "/ports"   2:8
number "80"        "/ports/0" 2:9
number "443"       "/ports/1" 2:13
]      ""          "/ports"   2:16
key    "db"        "/db"      3:1
{      ""          "/db"      3:5
key    "host"      "/db/host" 3:6
string "localhost" "/db/host" 3:12
}      ""          "/db"      3:21
}      ""          ""         3:22

Full source: docs/examples/conversion/jsontokens/example_test.go

ToJSONTokens reads nothing until the range starts. Each token holds:

  • Kind, one of nine: object and array start and end, key, string, number, bool and null. No token stands for a , or a :.
  • Value, the text of a key, a string or a number. A number keeps its digits.
  • At, the position of its first byte in the YAML source.

ts.Path() returns the RFC 6901 pointer of the token the loop is on. A key and its value share the pointer of their member. The YAML wrote no brace to close the document, so its } takes the position just past the last byte the mapping holds: 3:22, after the } of db.

Stop when you have it

ts := codec.ToJSONTokens([]byte(src))
for tok := range ts.Tokens() {
	if tok.Kind == codec.JSONString && ts.Path() == "/db/host" {
		fmt.Printf("%s at %d:%d\n", tok.Value, tok.At.Line, tok.At.Column)

		break
	}
}
fmt.Println("err:", ts.Err())

Full source: docs/examples/conversion/jsontokens/example_test.go

localhost at 3:12
err: <nil>

Full source: docs/examples/conversion/jsontokens/example_test.go

Breaking out of the range stops the parse. Err returns nil: a break is not an error, and nothing after db.host is read.

Check Err after the loop

ts := codec.ToJSONTokens([]byte(src + "timeout: .inf\n"))

n := 0
for range ts.Tokens() {
	n++
}
fmt.Println(n, "tokens")
fmt.Println(errors.Is(ts.Err(), yerrors.ErrNotJSON))

Full source: docs/examples/conversion/jsontokens/example_test.go

15 tokens
true

Full source: docs/examples/conversion/jsontokens/example_test.go

The loop body ran for every token before timeout: .inf, then the range ended, with nothing in the loop to show why. Err returns the error that stopped it. Call it after every range.

Cap the tokens

// 85 bytes, and "d" alone names 4 x 4 x 4 x 4 = 256 strings through its aliases.
const bomb = `a: &a [x, x, x, x]
b: &b [*a, *a, *a, *a]
c: &c [*b, *b, *b, *b]
d: [*c, *c, *c, *c]
`
ts := codec.ToJSONTokens([]byte(bomb)).Budget(100)
for range ts.Tokens() {
}
fmt.Println(ts.Err())

Full source: docs/examples/conversion/jsontokens/example_test.go

[3:16] the document hands over more than 100 JSON tokens
   1 | a: &a [x, x, x, x]
   2 | b: &b [*a, *a, *a, *a]
>  3 | c: &c [*b, *b, *b, *b]
                      ^
   4 | d: [*c, *c, *c, *c]

Full source: docs/examples/conversion/jsontokens/example_test.go

Each alias hands over everything its anchor names again, so a few hundred bytes can name more values than memory holds. Budget caps the tokens one document may hand over. The default, 0, sets no cap. Set one for input you did not write. The token past the cap stops the range, and Err returns an error that matches errors.ErrNotJSON, at that token’s position.

Variations

  • One buffer. ToJSON writes the same tokens, with the commas and colons, into one []byte. See YAML to JSON and back.
  • Reuse a buffer for the pointer. ts.AppendPath(dst) appends the pointer to dst.