πŸ“– 2 min read (~ 400 words).

YAMLPath

Reading a value by path

yml := `
store:
  book:
    - author: john
      price: 10
    - author: ken
      price: 12
  bicycle:
    color: red
    price: 19.95
`

path, err := expressions.PathString("$.store.book[*].author")
if err != nil {
	// ...
}

var authors []string
if err := path.Read(strings.NewReader(yml), &authors); err != nil {
	// ...
}
fmt.Println(authors) // [john ken]

The syntax

$the root
.a child
..recursive descent
[n]element n of a sequence
[*]every element of a sequence

A key containing . or * goes in single quotes: $.foo.'bar.baz-*'.hoge. A single quote inside that is escaped with a backslash.

expressions.PathBuilder builds the same paths in code β€” Root, Child, Index, IndexAll, Recursive, then Build β€” which is what you want when a segment comes from a variable rather than a literal.

Annotating the source

AnnotateSource returns the lines around the node, with a caret under it:

path, _ := expressions.PathString("$.a")
source, err := path.AnnotateSource([]byte(yml), false)
>  2 | a: 1
          ^
   3 | b: "hello"

The boolean is colored. Use it to report on a value your own code rejected after a successful decode β€” see Errors.

The godoc does not show the whole type

expressions.Path embeds an unexported engine, so go doc and pkg.go.dev list only Read and Filter. AnnotateSource, String, FilterNode, ReadNode and the merge and replace methods are promoted, callable, and invisible in the rendered documentation β€” the type’s own doc comment links to [Path.AnnotateSource], and that link goes nowhere.

Until that is fixed, this page is the list.

Working on nodes rather than values

Read and Filter go through the decoder and hand you a Go value. ReadNode and FilterNode stop at the tree, which is what you want when the document is the thing you are changing.

Errors

Four predicates, matching four sentinels: IsInvalidPathError, IsInvalidPathStringError, IsInvalidQueryError, IsNotFoundNodeError. A path that matches nothing is ErrNotFoundNode, not an empty result.

The same path strings key a CommentMap β€” see Comments.