query

package module
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 25, 2024 License: MIT Imports: 8 Imported by: 11

README

query-go

GoDoc 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 GoDoc.

Basic Usage

ParseString parses a query string and returns the query which extracts the value.

q, err := query.ParseString(`$.key[0].key['key']`)
v, err := q.Extract(target)

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 a index of array or slice

Documentation

Overview

Package query provides to extract the element from a Go value.

ParseString parses a query string and returns the query which extracts the value.

q, err := query.ParseString(`$.key[0].key['key']`)
v, err := q.Extract(target)

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 a index of array or slice

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsCaseInsensitive added in v1.3.0

func IsCaseInsensitive(ctx context.Context) bool

IsCaseInsensitive reports whether case-insensitive querying is enabled or not.

Types

type ExtractFunc added in v1.2.0

type ExtractFunc func(v reflect.Value) (reflect.Value, bool)

ExtractFunc represents a function to extracts a value.

type Extractor

type Extractor interface {
	Extract(v reflect.Value) (reflect.Value, bool)
	String() string
}

An Extractor interface is used by a query to extract the element from a value.

type Index

type Index struct {
	// contains filtered or unexported fields
}

Index represents an extractor to access the value by index.

func (*Index) Extract

func (e *Index) Extract(v reflect.Value) (reflect.Value, bool)

Extract extracts the value from v by index. It reports whether the index is found and returns the found value.

If v implements the IndexExtractor interface, this method extracts by calling v.ExtractByIndex.

func (*Index) String

func (e *Index) String() string

String returns e as string.

type IndexExtractor

type IndexExtractor interface {
	ExtractByIndex(index int) (interface{}, bool)
}

IndexExtractor is the interface that wraps the ExtractByIndex method.

ExtractByIndex extracts the value by index. It reports whether the index is found and returns the found value.

type Key

type Key struct {
	// contains filtered or unexported fields
}

Key represents an extractor to access the value by key.

func (*Key) Extract

func (e *Key) Extract(v reflect.Value) (reflect.Value, bool)

Extract extracts the value from v by key. It reports whether the key is found and returns the found value.

If v implements the KeyExtractor interface, this method extracts by calling v.ExtractByKey.

func (*Key) String

func (e *Key) String() string

String returns e as string.

type KeyExtractor

type KeyExtractor interface {
	ExtractByKey(key string) (interface{}, bool)
}

KeyExtractor is the interface that wraps the ExtractByKey method.

ExtractByKey extracts the value by key. It reports whether the key is found and returns the found value.

Example
package main

import (
	"fmt"

	"github.com/zoncoen/query-go"
)

type orderedMap struct {
	elems []*elem
}

type elem struct {
	k, v interface{}
}

func (m *orderedMap) ExtractByKey(key string) (interface{}, bool) {
	for _, e := range m.elems {
		if k, ok := e.k.(string); ok {
			if k == key {
				return e.v, true
			}
		}
	}
	return nil, false
}

func main() {
	q := query.New().Key("key")
	v, _ := q.Extract(&orderedMap{
		elems: []*elem{{k: "key", v: "value"}},
	})
	fmt.Println(v)
}
Output:

value

type KeyExtractorContext added in v1.3.0

type KeyExtractorContext interface {
	ExtractByKey(ctx context.Context, key string) (any, bool)
}

KeyExtractorContext is the interface that wraps the ExtractByKey method.

ExtractByKey extracts the value by key. It reports whether the key is found and returns the found value.

type Option

type Option func(*Query)

Option represents an option for Query.

func CaseInsensitive added in v1.2.0

func CaseInsensitive() Option

CaseInsensitive returns the Option to match case insensitivity.

Example
person := Person{
	Name: "Alice",
}
q := query.New(query.CaseInsensitive()).Key("NAME")
name, _ := q.Extract(person)
fmt.Println(name)
Output:

Alice

func CustomExtractFunc added in v1.2.0

func CustomExtractFunc(f func(ExtractFunc) ExtractFunc) Option

CustomExtractFunc returns the Option to customize the behavior of extractors.

Example
person := Person{
	Name: "Alice",
}
q := query.New(
	query.CustomExtractFunc(func(f query.ExtractFunc) query.ExtractFunc {
		return func(v reflect.Value) (reflect.Value, bool) {
			return reflect.ValueOf("Bob"), true
		}
	}),
).Key("name")
name, _ := q.Extract(person)
fmt.Println(name)
Output:

Bob

func CustomIsInlineStructFieldFunc added in v1.3.0

func CustomIsInlineStructFieldFunc(f func(reflect.StructField) bool) Option

CustomIsInlineStructFieldFunc returns the Option to customize the behavior of extractors.

func CustomStructFieldNameGetter deprecated

func CustomStructFieldNameGetter(f func(f reflect.StructField) string) Option

CustomStructFieldNameGetter returns the Option to set f as custom function which gets struct field name. f is called by Key.Extract to get struct field name, if the target value is a struct.

Deprecated: Use CustomExtractFunc instead.

Example
person := Person{
	Name: "Alice",
}

q := query.New(
	query.CustomStructFieldNameGetter(getFieldNameByJSONTag),
).Key("name")
name, _ := q.Extract(person)
fmt.Println(name)
Output:

Alice

func ExtractByStructTag added in v1.2.0

func ExtractByStructTag(tagNames ...string) Option

ExtractByStructTag returns the Option to allow extracting by struct tag.

Example
person := Person{
	Name: "Alice",
}
q := query.New(query.ExtractByStructTag("json")).Key("name")
name, _ := q.Extract(person)
fmt.Println(name)
Output:

Alice

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query represents a query to extract the element from a value.

func New

func New(opts ...Option) *Query

New returns a new query.

func Parse

func Parse(r io.Reader, opts ...Option) (*Query, error)

Parse parses a query string via r and returns the corresponding Query.

func ParseString

func ParseString(s string, opts ...Option) (*Query, error)

ParseString parses a query string s and returns the corresponding Query.

Example
package main

import (
	"fmt"

	"github.com/zoncoen/query-go"
)

type S struct {
	Maps []map[string]map[string]string
}

func main() {
	q, err := query.ParseString(`$.Maps[0].key['.key\'']`)
	if err == nil {
		v, _ := q.Extract(&S{
			Maps: []map[string]map[string]string{
				{"key": map[string]string{
					".key'": "value",
				}},
			},
		})
		fmt.Println(v)

	}
}
Output:

value

func (Query) Append

func (q Query) Append(es ...Extractor) *Query

Append appends extractor to q and returns updated q.

func (*Query) Extract

func (q *Query) Extract(target interface{}) (interface{}, error)

Extract extracts the value by q from target.

func (*Query) Extractors added in v1.1.0

func (q *Query) Extractors() []Extractor

Extractors returns query extractors of q.

func (Query) Index

func (q Query) Index(i int) *Query

Index is shorthand method to create Index and appends it.

func (Query) Key

func (q Query) Key(k string) *Query

Key is shorthand method to create Key and appends it.

func (Query) Root added in v1.2.0

func (q Query) Root() *Query

Root marks that q has an explicit root operator $.

func (*Query) String

func (q *Query) String() string

String returns q as string.

Directories

Path Synopsis
Package ast declares the types used to represent syntax trees.
Package ast declares the types used to represent syntax trees.
extractor
protobuf Module
yaml Module
Package parser implements a parser for a query string.
Package parser implements a parser for a query string.
Package token defines constants representing the lexical tokens.
Package token defines constants representing the lexical tokens.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL