This is a Go package to extract element from a Go value by a query string like $.key[0].key['key'].
See usage and example in the API reference.
ParseString parses a query string and returns the query which extracts the value.
import query "github.com/zoncoen/query-go/v2"
q, err := query.ParseString(`$.key[0].key['key']`)
v, err := q.Extract(ctx, target)When the queried element is absent, the returned error matches
query.ErrNotFound via errors.Is (and errors.As yields a
*query.NotFoundError carrying the failed position); any other error is an
extraction failure reported by an extractor, such as a context cancellation
that interrupted a blocking extractor.
-
The module path is
github.com/zoncoen/query-go/v2. The extractor modules moved with it:github.com/zoncoen/query-go/extractor/yaml/v2andgithub.com/zoncoen/query-go/extractor/protobuf/v2. Their v1 paths keep the v1 API —extractor/yaml v0.3.0andextractor/protobuf v0.2.0shipped the v2 API under the v1 path by mistake and are retracted. -
Query.Extracttakes acontext.Context;ExtractContextis gone. -
The extractor interfaces are consolidated:
KeyExtractorandIndexExtractornow take a context and return(any, error)— returnquery.ErrNotFoundfor an absent element instead offalse. The...Contextinterface variants are gone. -
ExtractFuncisfunc(ctx context.Context, v reflect.Value) (reflect.Value, error). -
Extractors can now report failures distinct from absence: any non-ErrNotFound error aborts the extraction and is returned to the caller.
-
A type that is not migrated silently stops satisfying the interfaces and falls back to reflection-based extraction. Add a compile-time assertion to each implementation to catch this:
var _ query.KeyExtractor = (*MyType)(nil)
The query syntax understood by this package when parsing is as follows.
$ the root element
.key extracts by a key of map or field name of struct ("." can be omitted if the head of query)
['key'] same as the ".key" (if the key contains "\" or "'", these characters must be escaped like "\\", "\'")
[0] extracts by an index of array or slice (a negative index counts from the end: [-1] is the last element), or by an integer key of map