Skip to content

Latest commit

 

History

200 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

query-go

Go Reference coverage ratio Go Report Card LICENSE

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.

Basic Usage

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.

Migrating from v1

  • The module path is github.com/zoncoen/query-go/v2. The extractor modules moved with it: github.com/zoncoen/query-go/extractor/yaml/v2 and github.com/zoncoen/query-go/extractor/protobuf/v2. Their v1 paths keep the v1 API — extractor/yaml v0.3.0 and extractor/protobuf v0.2.0 shipped the v2 API under the v1 path by mistake and are retracted.

  • Query.Extract takes a context.Context; ExtractContext is gone.

  • The extractor interfaces are consolidated: KeyExtractor and IndexExtractor now take a context and return (any, error) — return query.ErrNotFound for an absent element instead of false. The ...Context interface variants are gone.

  • ExtractFunc is func(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)

Query Syntax

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

About

This is a Go package to extract value by a query string.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages