tree

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2023 License: MIT Imports: 13 Imported by: 4

README

Tree

PkgGoDev Report Card

Tree is a simple structure for dealing with dynamic or unknown JSON/YAML in Go.

Features

  • Parses json/yaml of unknown structure to get to nodes with fluent interface.
  • Syntax similar to Go standard and map and slice.
  • Find function can be specified the Query expression.
  • Edit function can be specified the Edit expression.
  • Bundled 'tq' that is a portable command-line JSON/YAML processor.

Road to 1.0

  • Placeholders in query.
  • Merging nodes.

Syntax

Go
tree.Map{
	"ID":     tree.ToValue(1),
	"Name":   tree.ToValue("Reds"),
	"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
}
JSON
{
	"ID": 1,
	"Name": "Reds",
	"Colors": ["Crimson", "Red", "Ruby", "Maroon"]
}
YAML
ID: 1
Name: Reds
Colors:
- Crimson
- Red
- Ruby
- Maroon

Marshal and Unmarshal

func ExampleMarshalJSON() {
	group := tree.Map{
		"ID":     tree.ToValue(1),
		"Name":   tree.ToValue("Reds"),
		"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
	}
	b, err := json.Marshal(group)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))

	// Output:
	// {"Colors":["Crimson","Red","Ruby","Maroon"],"ID":1,"Name":"Reds"}
}
func ExampleUnmarshalJSON() {
	data := []byte(`[
  {"Name": "Platypus", "Order": "Monotremata"},
  {"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`)

	var animals tree.Array
	err := json.Unmarshal(data, &animals)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", animals)

	// Output:
	// [map[Name:Platypus Order:Monotremata] map[Name:Quoll Order:Dasyuromorphia]]
}
Using other parsers

Tree may works on other parsers those has compatible with "encoding/json" or "gopkg.in/yaml.v2". See examples directory.

Alternate json.RawMessage

For example, Dynamic JSON in Go shows an example of using json.RawMessage.

It may be simpler to use tree.Map instead of json.RawMessage.

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/jarxorg/tree"
)

const input = `
{
	"type": "sound",
	"msg": {
		"description": "dynamite",
		"authority": "the Bruce Dickinson"
	}
}
`

type Envelope struct {
	Type string
	Msg  tree.Map
}

func main() {
	env := Envelope{}
	if err := json.Unmarshal([]byte(input), &env); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%#v\n", env)
	fmt.Printf("%#v\n", env.Msg.Get("description"))

	// Output:
	// main.Envelope{Type:"sound", Msg:tree.Map{"authority":"the Bruce Dickinson", "description":"dynamite"}}
	// "dynamite"
}

Get

func ExampleGet() {
	group := tree.Map{
		"ID":     tree.ToValue(1),
		"Name":   tree.ToValue("Reds"),
		"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
		"Nil":    nil,
	}
	fmt.Println(group.Get("Colors").Get(1))
	fmt.Println(group.Get("Colors", 2))
	fmt.Println(group.Get("Colors").Get(5).IsNil())
	fmt.Println(group.Get("Nil").IsNil())

	// Output:
	// Red
	// Ruby
	// true
	// true
}

Find

func ExampleFind() {
	group := tree.Map{
		"ID":     tree.ToValue(1),
		"Name":   tree.ToValue("Reds"),
		"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
	}

	rs, err := group.Find(".Colors[1:3]")
	if err != nil {
		log.Fatal(err)
	}
	for _, r := range rs {
		fmt.Println(r)
	}

	// Output:
	// Red
	// Ruby
}
Query
Query Description Results
.store.book[0] The first book {"category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95}
.store.book[0].price The price of the first book 8.95
.store.book.0.price The price of the first book (using dot) 8.95
.store.book[:2].price All prices of books[0:2] (index 2 is exclusive) 8.95, 12.99
.store.book[].author All authors of all books "Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"
..author All authors "Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"
..author | [0] The first author "Nigel Rees"
.store.book[(.category == "fiction" or .category == "reference") and .price < 10].title All titles of books these are categoried into "fiction", "reference" and price < 10 "Sayings of the Century", "Moby Dick"
.store.book[.title ~= "^S"].title Titles beginning with "S" "Sayings of the Century", "Sword of Honour"
.store.book.count() Count books 4
.store.book[0].keys() Sorted keys of the first book ["author", "category", "price", "title"]
.store.book[0].values() Values of the first book ["Nigel Rees", "reference", 8.95, "Sayings of the Century"]
Illustrative Object
{
  "store": {
    "book": [{
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

Edit

func ExampleEdit() {
	var group tree.Node = tree.Map{
		"ID":     tree.ToValue(1),
		"Name":   tree.ToValue("Reds"),
		"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
	}

	if err := tree.Edit(&group, ".Colors += \"Pink\""); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Append Pink to Colors:\n  %+v\n", group)

	if err := tree.Edit(&group, ".Name = \"Blue\""); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Set Blue to Name:\n  %+v\n", group)

	if err := tree.Edit(&group, ".Colors ^?"); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Delete Colors:\n  %+v\n", group)

	// Output:
	// Append Pink to Colors:
	//   map[Colors:[Crimson Red Ruby Maroon Pink] ID:1 Name:Reds]
	// Set Blue to Name:
	//   map[Colors:[Crimson Red Ruby Maroon Pink] ID:1 Name:Blue]
	// Delete Colors:
	//   map[ID:1 Name:Blue]
}

tq

tq is a portable command-line JSON/YAML processor.

Installation
go install github.com/jarxorg/tree/cmd/tq@latest

Using Homebrew

brew tap jarxorg/tree
brew install jarxorg/tree/tq

Download binary

VERSION=0.8.0 GOOS=Darwin GOARCH=arm64; curl -fsSL "https://github.com/jarxorg/tree/releases/download/v${VERSION}/tree_${VERSION}_${GOOS}_${GOARCH}.tar.gz" | tar xz tq && mv tq /usr/local/bin
Usage
tq is a command-line JSON/YAML processor.

Usage:
  tq [flags] [query] ([file...])

Flags:
  -c, --color                  output with colors
  -e, --edit stringArray       edit expression
  -x, --expand                 expand results
  -h, --help                   help for tq
  -U, --inplace                update files, inplace
  -i, --input-format string    input format (json or yaml)
  -j, --input-json             alias --input-format json
  -y, --input-yaml             alias --input-format yaml
  -O, --output string          output file
  -o, --output-format string   output format (json or yaml, default json)
  -J, --output-json            alias --output-format json
  -Y, --output-yaml            alias --output-format yaml
  -r, --raw                    output raw strings
  -s, --slurp                  slurp all results into an array
  -t, --template string        golang text/template string
  -v, --version                print version

Examples:
  % echo '{"colors": ["red", "green", "blue"]}' | tq '.colors[0]'
  "red"

  % echo '{"users":[{"id":1,"name":"one"},{"id":2,"name":"two"}]}' | tq -x -t '{{.id}}: {{.name}}' '.users'
  1: one
  2: two

  % echo '{}' | tq -e '.colors = ["red", "green"]' -e '.colors += "blue"' .
  {
    "colors": [
      "red",
      "green",
      "blue"
    ]
  }

for jq user
tq jq
tq '.store.book[0]' jq '.store.book[0]'
tq '.store.book[]' jq '.store.book[]'
tq '.store.book[:2].price' jq '.store.book[:2][] | .price'
tq '.store.book[.category == "fiction" and .price < 10].title' jq '.store.book[] | select(.category == "fiction" and .price < 10) | .title'

Third-party library licenses

Documentation

Overview

Package tree provides a simple structure for dealing with dynamic or unknown JSON/YAML structures.

Index

Examples

Constants

View Source
const VERSION = "0.8.0"

VERSION is the version number.

Variables

View Source
var (
	Nil = NilValue{}
)
View Source
var SkipWalk = errors.New("skip")

SkipWalk is used as a return value from WalkFunc to indicate that the node and that children in the call is to be skipped. It is not returned as an error by any function.

Functions

func Edit added in v0.5.0

func Edit(pn *Node, expr string) error
Example
package main

import (
	"fmt"
	"log"

	"github.com/jarxorg/tree"
)

func main() {
	var group tree.Node = tree.Map{
		"ID":     tree.ToValue(1),
		"Name":   tree.ToValue("Reds"),
		"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
	}

	if err := tree.Edit(&group, ".Colors += \"Pink\""); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Append Pink to Colors:\n  %+v\n", group)

	if err := tree.Edit(&group, ".Name = \"Blue\""); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Set Blue to Name:\n  %+v\n", group)

	if err := tree.Edit(&group, ".Colors ^?"); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Delete Colors:\n  %+v\n", group)

}
Output:

Append Pink to Colors:
  map[Colors:[Crimson Red Ruby Maroon Pink] ID:1 Name:Reds]
Set Blue to Name:
  map[Colors:[Crimson Red Ruby Maroon Pink] ID:1 Name:Blue]
Delete Colors:
  map[ID:1 Name:Blue]

func MarshalJSON

func MarshalJSON(n Node) ([]byte, error)

MarshalJSON returns the JSON encoding of the specified node.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/jarxorg/tree"
)

func main() {
	group := tree.Map{
		"ID":     tree.ToValue(1),
		"Name":   tree.ToValue("Reds"),
		"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
	}
	b, err := json.Marshal(group)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))

}
Output:

{"Colors":["Crimson","Red","Ruby","Maroon"],"ID":1,"Name":"Reds"}
Example (Combined)
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/jarxorg/tree"
)

func main() {
	type ColorGroup struct {
		ID     int
		Name   string
		Colors tree.Array
	}
	group := ColorGroup{
		ID:     1,
		Name:   "Reds",
		Colors: tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
	}
	b, err := json.Marshal(group)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))

}
Output:

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}

func MarshalYAML

func MarshalYAML(n Node) ([]byte, error)

MarshalYAML returns the YAML encoding of the specified node.

Example
group := tree.Map{
	"ID":     tree.ToValue(1),
	"Name":   tree.ToValue("Reds"),
	"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
}
b, err := yaml.Marshal(group)
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(b))
Output:

Colors:
- Crimson
- Red
- Ruby
- Maroon
ID: 1
Name: Reds

func OutputColorJSON added in v0.7.2

func OutputColorJSON(out io.Writer, n Node) error

OutputColorJSON writes JSON values with color to out.

func OutputColorYAML added in v0.7.2

func OutputColorYAML(out io.Writer, n Node) error

OutputColorYAML writes YAML values with color to out.

func ToAny added in v0.7.2

func ToAny(n Node) interface{}

func UnmarshalViaJSON added in v0.6.3

func UnmarshalViaJSON(n Node, v interface{}) error

UnmarshalViaJSON stores the node in the value pointed to by v via "encoding/json".

func UnmarshalViaYAML added in v0.6.3

func UnmarshalViaYAML(n Node, v interface{}) error

UnmarshalViaYAML stores the node in the value pointed to by v via "gopkg.in/yaml.v2".

func Walk added in v0.2.0

func Walk(n Node, fn WalkFunc) error

Walk walks the node tree rooted at root, calling fn for each node or that children in the tree, including root.

Types

type And added in v0.4.0

type And []Selector

And represents selectors that combines each selector with and.

func (And) Matches added in v0.4.0

func (a And) Matches(n Node) (bool, error)

Matches returns true if all selectors returns true.

func (And) String added in v0.5.0

func (a And) String() string

type Any added in v0.8.0

type Any struct {
	Node
}

Any is an interface that defines any node.

func (Any) Array added in v0.8.0

func (n Any) Array() Array

Array returns this node as an Array.

func (Any) Each added in v0.8.0

func (n Any) Each(cb func(key interface{}, n Node) error) error

Each calls the callback function for each Array values.

func (Any) Find added in v0.8.0

func (n Any) Find(expr string) ([]Node, error)

Find finds a node using the query expression.

func (Any) Get added in v0.8.0

func (n Any) Get(keys ...interface{}) Node

Get returns an array value as Node.

func (Any) Has added in v0.8.0

func (n Any) Has(keys ...interface{}) bool

Has checks this node has key.

func (Any) IsNil added in v0.8.0

func (n Any) IsNil() bool

IsNil returns true if this node is nil.

func (Any) Map added in v0.8.0

func (n Any) Map() Map

Map returns nil.

func (Any) Type added in v0.8.0

func (n Any) Type() Type

Type returns TypeArray.

func (*Any) UnmarshalJSON added in v0.8.0

func (n *Any) UnmarshalJSON(data []byte) error

UnmarshalJSON is an implementation of json.Unmarshaler.

func (Any) Value added in v0.8.0

func (n Any) Value() Value

Value returns nil.

type Array

type Array []Node

Array represents an array of Node.

func ToArrayValues added in v0.2.0

func ToArrayValues(vs ...interface{}) Array

ToArrayValues calss ToValues for each provided vs and returns them as an Array.

func (*Array) Append added in v0.5.0

func (n *Array) Append(v Node) error

Append appends v to *n.

func (Array) Array

func (n Array) Array() Array

Array returns this node as an Array.

func (*Array) Delete added in v0.5.0

func (n *Array) Delete(key interface{}) error

Delete deletes n[key].

func (Array) Each added in v0.3.0

func (n Array) Each(cb func(key interface{}, n Node) error) error

Each calls the callback function for each Array values.

func (Array) Find added in v0.5.0

func (n Array) Find(expr string) ([]Node, error)

Find finds a node using the query expression.

func (Array) Get added in v0.1.1

func (n Array) Get(keys ...interface{}) Node

Get returns an array value as Node.

func (Array) Has added in v0.5.0

func (n Array) Has(keys ...interface{}) bool

Has checks this node has key.

func (Array) IsNil added in v0.6.0

func (n Array) IsNil() bool

IsNil returns true if this node is nil.

func (Array) Map

func (n Array) Map() Map

Map returns nil.

func (*Array) Set added in v0.5.0

func (n *Array) Set(key interface{}, v Node) error

Set sets v to n[key].

func (Array) Type

func (n Array) Type() Type

Type returns TypeArray.

func (*Array) UnmarshalJSON

func (n *Array) UnmarshalJSON(data []byte) error

UnmarshalJSON is an implementation of json.Unmarshaler.

func (*Array) UnmarshalYAML

func (n *Array) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML is an implementation of yaml.Unmarshaler.

func (Array) Value

func (n Array) Value() Value

Value returns nil.

type ArrayQuery added in v0.2.0

type ArrayQuery int

ArrayQuery is an index of the Array that implements methods of the Query.

func (ArrayQuery) Append added in v0.5.0

func (q ArrayQuery) Append(pn *Node, v Node) error

func (ArrayQuery) Delete added in v0.5.0

func (q ArrayQuery) Delete(pn *Node) error

func (ArrayQuery) Exec added in v0.2.0

func (q ArrayQuery) Exec(n Node) ([]Node, error)

func (ArrayQuery) Set added in v0.5.0

func (q ArrayQuery) Set(pn *Node, v Node) error

func (ArrayQuery) String added in v0.5.0

func (q ArrayQuery) String() string

type ArrayRangeQuery added in v0.2.0

type ArrayRangeQuery []int

ArrayRangeQuery represents a range of the Array that implements methods of the Query.

func (ArrayRangeQuery) Exec added in v0.2.0

func (q ArrayRangeQuery) Exec(n Node) ([]Node, error)

func (ArrayRangeQuery) String added in v0.5.0

func (q ArrayRangeQuery) String() string

type BoolValue

type BoolValue bool

A BoolValue represents a bool value.

func (BoolValue) Array

func (n BoolValue) Array() Array

Array returns nil.

func (BoolValue) Bool

func (n BoolValue) Bool() bool

Bool returns this.

func (BoolValue) Compare added in v0.2.0

func (n BoolValue) Compare(op Operator, v Value) bool

Compare compares n and v.

func (BoolValue) Each added in v0.3.0

func (n BoolValue) Each(cb func(key interface{}, n Node) error) error

Each calls cb(nil, n).

func (BoolValue) Find added in v0.5.0

func (n BoolValue) Find(expr string) ([]Node, error)

Find finds a node using the query expression.

func (BoolValue) Float64

func (n BoolValue) Float64() float64

Float64 returns 0.

func (BoolValue) Get added in v0.1.1

func (n BoolValue) Get(keys ...interface{}) Node

Get returns nil.

func (BoolValue) Has added in v0.5.0

func (n BoolValue) Has(keys ...interface{}) bool

Has returns false.

func (BoolValue) Int

func (n BoolValue) Int() int

Int returns 0.

func (BoolValue) Int64

func (n BoolValue) Int64() int64

Int64 returns 0.

func (BoolValue) IsNil added in v0.6.0

func (n BoolValue) IsNil() bool

IsNil returns true if this node is nil.

func (BoolValue) Map

func (n BoolValue) Map() Map

Map returns nil.

func (BoolValue) String

func (n BoolValue) String() string

String returns this as string.

func (BoolValue) Type

func (n BoolValue) Type() Type

Type returns TypeValue.

func (BoolValue) Value

func (n BoolValue) Value() Value

Value returns this.

type ColorEncoder added in v0.7.2

type ColorEncoder struct {
	Out        io.Writer
	IndentSize int
	NoColor    bool
	// contains filtered or unexported fields
}

ColorEncoder writes JSON or YAML values with color to an output stream.

func (*ColorEncoder) EncodeJSON added in v0.7.2

func (e *ColorEncoder) EncodeJSON(n Node) error

EncodeJSON writes JSON values with color to an output stream.

func (*ColorEncoder) EncodeYAML added in v0.7.2

func (e *ColorEncoder) EncodeYAML(n Node) error

EncodeJSON writes JSON values with color to an output stream.

type Comparator added in v0.2.0

type Comparator struct {
	Left  Query
	Op    Operator
	Right Query
}

Comparator represents a comparable selector.

func (Comparator) Matches added in v0.2.0

func (c Comparator) Matches(n Node) (bool, error)

Matches evaluates left and right using the operator. (eg. .id == 0)

func (Comparator) String added in v0.5.0

func (c Comparator) String() string

type CountQuery added in v0.8.0

type CountQuery struct{}

func (CountQuery) Exec added in v0.8.0

func (q CountQuery) Exec(n Node) ([]Node, error)

func (CountQuery) String added in v0.8.0

func (q CountQuery) String() string

type EditorNode added in v0.5.0

type EditorNode interface {
	Node
	Append(v Node) error
	Set(key interface{}, v Node) error
	Delete(key interface{}) error
}

EditorNode is an interface that defines the methods to edit this node.

type EditorQuery added in v0.5.0

type EditorQuery interface {
	Query
	Set(pn *Node, v Node) error
	Append(pn *Node, v Node) error
	Delete(pn *Node) error
}

EditorQuery is an interface that defines the methods to edit a node.

type FilterQuery added in v0.2.0

type FilterQuery []Query

FilterQuery consists of multiple queries that filter the nodes in order.

func (FilterQuery) Exec added in v0.2.0

func (qs FilterQuery) Exec(n Node) ([]Node, error)

func (FilterQuery) String added in v0.5.0

func (qs FilterQuery) String() string

type KeysQuery added in v0.8.0

type KeysQuery struct{}

func (KeysQuery) Exec added in v0.8.0

func (q KeysQuery) Exec(n Node) ([]Node, error)

func (KeysQuery) String added in v0.8.0

func (q KeysQuery) String() string

type Map

type Map map[string]Node

Map represents a map of Node.

func (Map) Append added in v0.5.0

func (n Map) Append(v Node) error

Append returns a error.

func (Map) Array

func (n Map) Array() Array

Array returns nil.

func (Map) Delete added in v0.5.0

func (n Map) Delete(key interface{}) error

Delete deletes n[key].

func (Map) Each added in v0.3.0

func (n Map) Each(cb func(key interface{}, n Node) error) error

Each calls the callback function for each Map values.

func (Map) Find added in v0.5.0

func (n Map) Find(expr string) ([]Node, error)

Find finds a node using the query expression.

func (Map) Get added in v0.1.1

func (n Map) Get(keys ...interface{}) Node

Get returns an array value as Node.

func (Map) Has added in v0.5.0

func (n Map) Has(keys ...interface{}) bool

Has checks this node has key.

func (Map) IsNil added in v0.6.0

func (n Map) IsNil() bool

IsNil returns true if this node is nil.

func (Map) Keys added in v0.5.0

func (n Map) Keys() []string

Keys returns sorted keys of the map.

func (Map) Map

func (n Map) Map() Map

Map returns this node as a Map.

func (Map) Set added in v0.5.0

func (n Map) Set(key interface{}, v Node) error

Set sets v to n[key].

func (Map) Type

func (n Map) Type() Type

Type returns TypeMap.

func (*Map) UnmarshalJSON

func (n *Map) UnmarshalJSON(data []byte) error

UnmarshalJSON is an implementation of json.Unmarshaler.

func (*Map) UnmarshalYAML

func (n *Map) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML is an implementation of yaml.Unmarshaler.

func (Map) Value

func (n Map) Value() Value

Value returns nil.

func (Map) Values added in v0.5.0

func (n Map) Values() []Node

Values returns values of the map.

type MapQuery added in v0.2.0

type MapQuery string

MapQuery is a key of the Map that implements methods of the Query.

func (MapQuery) Append added in v0.5.0

func (q MapQuery) Append(pn *Node, v Node) error

func (MapQuery) Delete added in v0.5.0

func (q MapQuery) Delete(pn *Node) error

func (MapQuery) Exec added in v0.2.0

func (q MapQuery) Exec(n Node) ([]Node, error)

func (MapQuery) Set added in v0.5.0

func (q MapQuery) Set(pn *Node, v Node) error

func (MapQuery) String added in v0.5.0

func (q MapQuery) String() string

type NilValue added in v0.6.0

type NilValue struct{}

func (NilValue) Array added in v0.6.0

func (n NilValue) Array() Array

Array returns nil.

func (NilValue) Bool added in v0.6.0

func (n NilValue) Bool() bool

Bool returns false.

func (NilValue) Compare added in v0.6.0

func (n NilValue) Compare(op Operator, v Value) bool

Compare compares n and v.

func (NilValue) Each added in v0.6.0

func (n NilValue) Each(cb func(key interface{}, n Node) error) error

Each calls cb(nil, n).

func (NilValue) Find added in v0.6.0

func (n NilValue) Find(expr string) ([]Node, error)

Find finds a node using the query expression.

func (NilValue) Float64 added in v0.6.0

func (n NilValue) Float64() float64

Float64 returns 0.

func (NilValue) Get added in v0.6.0

func (n NilValue) Get(keys ...interface{}) Node

Get returns nil.

func (NilValue) Has added in v0.6.0

func (n NilValue) Has(keys ...interface{}) bool

Has returns false.

func (NilValue) Int added in v0.6.0

func (n NilValue) Int() int

Int returns 0.

func (NilValue) Int64 added in v0.6.0

func (n NilValue) Int64() int64

Int64 returns 0.

func (NilValue) IsNil added in v0.6.0

func (n NilValue) IsNil() bool

IsNil returns true if this node is nil.

func (NilValue) Map added in v0.6.0

func (n NilValue) Map() Map

Map returns nil.

func (NilValue) MarshalJSON added in v0.6.0

func (n NilValue) MarshalJSON() ([]byte, error)

MarshalJSON is an implementation of json.Marshaler.

func (NilValue) MarshalYAML added in v0.6.0

func (n NilValue) MarshalYAML() (interface{}, error)

MarshalYAML is an implementation of yaml.Marshaler.

func (NilValue) String added in v0.6.0

func (n NilValue) String() string

String returns this as string.

func (NilValue) Type added in v0.6.0

func (n NilValue) Type() Type

Type returns TypeValue.

func (NilValue) Value added in v0.6.0

func (n NilValue) Value() Value

Value returns this.

type Node

type Node interface {
	// IsNil returns true if this node is nil.
	IsNil() bool
	// Type returns this node type.
	Type() Type
	// Array returns this node as an Array.
	// If this type is not Array, returns a Array(nil).
	Array() Array
	// Map returns this node as a Map.
	// If this type is not Map, returns a Map(nil).
	Map() Map
	// Value returns this node as a Value.
	// If this type is not Value, returns a NilValue.
	Value() Value
	// Has checks this node has key.
	Has(keys ...interface{}) bool
	// Get returns array/map value that matched by the specified key.
	// The key type allows int or string.
	// If the specified keys does not match, returns NilValue.
	Get(keys ...interface{}) Node
	// Each calls the callback function for each Array|Map values.
	// If the node type is not Array|Map then the callback called once with nil key and self as value.
	Each(cb func(key interface{}, v Node) error) error
	// Find finds a node using the query expression.
	Find(expr string) ([]Node, error)
}

A Node is an element on the tree.

func DecodeJSON added in v0.2.0

func DecodeJSON(dec *json.Decoder) (Node, error)

DecodeJSON decodes JSON as a node using the provided decoder.

func DecodeYAML added in v0.2.0

func DecodeYAML(dec *yaml.Decoder) (Node, error)

DecodeYAML decodes YAML as a node using the provided decoder.

func Find added in v0.2.0

func Find(n Node, expr string) ([]Node, error)

Find finds a node from n using the Query.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jarxorg/tree"
)

func main() {
	group := tree.Map{
		"ID":     tree.ToValue(1),
		"Name":   tree.ToValue("Reds"),
		"Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
	}

	rs, err := group.Find(".Colors[1:3]")
	if err != nil {
		log.Fatal(err)
	}
	for _, r := range rs {
		fmt.Println(r)
	}

}
Output:

Red
Ruby

func MarshalViaJSON added in v0.6.3

func MarshalViaJSON(v interface{}) (Node, error)

MarshalViaJSON returns the node encoding of v via "encoding/json".

func MarshalViaYAML added in v0.6.3

func MarshalViaYAML(v interface{}) (Node, error)

MarshalViaYAML returns the node encoding of v via "gopkg.in/yaml.v2".

func ToNode

func ToNode(v interface{}) Node

ToNode converts the specified v to an Node.

func ToNodeValues added in v0.5.0

func ToNodeValues(vs ...interface{}) []Node

ToNodeValues calss ToValues for each provided vs and returns them as []Node.

func ToValue

func ToValue(v interface{}) Node

ToValue converts the specified v to a Value as Node. Node.Value() returns converted value.

func UnmarshalJSON

func UnmarshalJSON(data []byte) (Node, error)

UnmarshalJSON parses the JSON-encoded data to a Node.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/jarxorg/tree"
)

func main() {
	data := []byte(`[
  {"Name": "Platypus", "Order": "Monotremata"},
  {"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`)

	var animals tree.Array
	err := json.Unmarshal(data, &animals)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%v\n", animals)

}
Output:

[map[Name:Platypus Order:Monotremata] map[Name:Quoll Order:Dasyuromorphia]]
Example (Any)
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/jarxorg/tree"
)

func main() {
	data := []byte(`[
  {"Name": "Platypus", "Order": "Monotremata"},
  {"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`)

	var animals tree.Any
	err := json.Unmarshal(data, &animals)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%v\n", animals.Type().IsArray())
	fmt.Printf("%v\n", animals.Array())

}
Output:

true
[map[Name:Platypus Order:Monotremata] map[Name:Quoll Order:Dasyuromorphia]]
Example (Combined)
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/jarxorg/tree"
)

func main() {
	data := []byte(`[
  {"Name": "Platypus", "Order": "Monotremata"},
  {"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`)
	type Animal struct {
		Name  string
		Order tree.StringValue
	}
	var animals []Animal
	err := json.Unmarshal(data, &animals)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", animals)

}
Output:

[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]

func UnmarshalYAML

func UnmarshalYAML(data []byte) (Node, error)

UnmarshalYAML returns the YAML encoding of the specified node.

Example
data := []byte(`---
Colors:
- Crimson
- Red
- Ruby
- Maroon
ID: 1
Name: Reds
`)

var group tree.Map
if err := yaml.Unmarshal(data, &group); err != nil {
	log.Fatal(err)
}
fmt.Printf("%+v\n", group)
Output:

map[Colors:[Crimson Red Ruby Maroon] ID:1 Name:Reds]

type NopQuery added in v0.2.0

type NopQuery struct{}

NopQuery is a query that implements no-op Exec method.

func (NopQuery) Append added in v0.5.0

func (q NopQuery) Append(pn *Node, v Node) error

func (NopQuery) Delete added in v0.5.0

func (q NopQuery) Delete(pn *Node) error

func (NopQuery) Exec added in v0.5.0

func (q NopQuery) Exec(n Node) ([]Node, error)

Exec returns the provided node.

func (NopQuery) Set added in v0.5.0

func (q NopQuery) Set(pn *Node, v Node) error

func (NopQuery) String added in v0.5.0

func (q NopQuery) String() string

type NumberValue

type NumberValue float64

A NumberValue represents an number value.

func (NumberValue) Array

func (n NumberValue) Array() Array

Array returns nil.

func (NumberValue) Bool

func (n NumberValue) Bool() bool

Bool returns false.

func (NumberValue) Compare added in v0.2.0

func (n NumberValue) Compare(op Operator, v Value) bool

Compare compares n and v.

func (NumberValue) Each added in v0.3.0

func (n NumberValue) Each(cb func(key interface{}, n Node) error) error

Each calls cb(nil, n).

func (NumberValue) Find added in v0.5.0

func (n NumberValue) Find(expr string) ([]Node, error)

Find finds a node using the query expression.

func (NumberValue) Float64

func (n NumberValue) Float64() float64

Float64 returns float64(n).

func (NumberValue) Get added in v0.1.1

func (n NumberValue) Get(keys ...interface{}) Node

Get returns nil.

func (NumberValue) Has added in v0.5.0

func (n NumberValue) Has(keys ...interface{}) bool

Has returns false.

func (NumberValue) Int

func (n NumberValue) Int() int

Int returns int(n).

func (NumberValue) Int64

func (n NumberValue) Int64() int64

Int64 returns int64(n).

func (NumberValue) IsNil added in v0.6.0

func (n NumberValue) IsNil() bool

IsNil returns true if this node is nil.

func (NumberValue) Map

func (n NumberValue) Map() Map

Map returns nil.

func (NumberValue) String

func (n NumberValue) String() string

String returns this as string using strconv.FormatFloat(float64(n), 'f', -1, 64).

func (NumberValue) Type

func (n NumberValue) Type() Type

Type returns TypeValue.

func (NumberValue) Value

func (n NumberValue) Value() Value

Value returns this.

type Operator added in v0.2.0

type Operator string

Operator represents an operator.

var (
	// EQ is `==`.
	EQ Operator = "=="
	// GT is `>`.
	GT Operator = ">"
	// GE is `>=`.
	GE Operator = ">="
	// LT is `<`.
	LT Operator = "<"
	// LE is `<=`.
	LE Operator = "<="
	// NE is `!=`
	NE Operator = "!="
	// RE is `~=`
	RE Operator = "~="
)

type Or added in v0.4.0

type Or []Selector

Or represents selectors that combines each selector with or.

func (Or) Matches added in v0.4.0

func (o Or) Matches(n Node) (bool, error)

Matches returns true if anyone returns true.

func (Or) String added in v0.5.0

func (o Or) String() string

type Query added in v0.2.0

type Query interface {
	Exec(n Node) ([]Node, error)
	String() string
}

Query is an interface that defines the methods to query a node.

func ParseQuery added in v0.2.0

func ParseQuery(expr string) (Query, error)

ParseQuery parses the provided expr to a Query. See https://github.com/jarxorg/tree#Query

type SelectQuery added in v0.2.0

type SelectQuery struct {
	Selector
}

SelectQuery returns nodes that matched by selectors.

func (SelectQuery) Exec added in v0.2.0

func (q SelectQuery) Exec(n Node) ([]Node, error)

func (SelectQuery) String added in v0.5.0

func (q SelectQuery) String() string

type Selector added in v0.2.0

type Selector interface {
	Matches(n Node) (bool, error)
	String() string
}

Selector checks if a node is eligible for selection.

type SlurpQuery added in v0.5.0

type SlurpQuery struct{}

SlurpQuery is a special query that works in FilterQuery.

func (SlurpQuery) Exec added in v0.5.0

func (q SlurpQuery) Exec(n Node) ([]Node, error)

Exec returns the provided node into a single node array. FilterQuery calls q.Exec(Array(results)), which has the effect of to slurp all the results into a single node array.

func (SlurpQuery) String added in v0.5.0

func (q SlurpQuery) String() string

type StringValue

type StringValue string

A StringValue represents a string value.

func (StringValue) Array

func (n StringValue) Array() Array

Array returns nil.

func (StringValue) Bool

func (n StringValue) Bool() bool

Bool returns false.

func (StringValue) Compare added in v0.2.0

func (n StringValue) Compare(op Operator, v Value) bool

Compare compares n and v.

func (StringValue) Each added in v0.3.0

func (n StringValue) Each(cb func(key interface{}, n Node) error) error

Each calls cb(nil, n).

func (StringValue) Find added in v0.5.0

func (n StringValue) Find(expr string) ([]Node, error)

Find finds a node using the query expression.

func (StringValue) Float64

func (n StringValue) Float64() float64

Float64 returns 0.

func (StringValue) Get added in v0.1.1

func (n StringValue) Get(keys ...interface{}) Node

Get returns nil.

func (StringValue) Has added in v0.5.0

func (n StringValue) Has(keys ...interface{}) bool

Has returns false.

func (StringValue) Int

func (n StringValue) Int() int

Int returns 0.

func (StringValue) Int64

func (n StringValue) Int64() int64

Int64 returns 0.

func (StringValue) IsNil added in v0.6.0

func (n StringValue) IsNil() bool

IsNil returns true if this node is nil.

func (StringValue) Map

func (n StringValue) Map() Map

Map returns nil.

func (StringValue) String

func (n StringValue) String() string

String returns this as string.

func (StringValue) Type

func (n StringValue) Type() Type

Type returns TypeValue.

func (StringValue) Value

func (n StringValue) Value() Value

Value returns this.

type Type

type Type int

Type represents the Node type.

const (
	TypeArray       Type = 0b0001
	TypeMap         Type = 0b0010
	TypeValue       Type = 0b1000
	TypeNilValue    Type = 0b1001
	TypeStringValue Type = 0b1010
	TypeBoolValue   Type = 0b1011
	TypeNumberValue Type = 0b1100
)

These variables are the Node types.

func (Type) IsArray

func (t Type) IsArray() bool

IsArray returns t == TypeArray.

func (Type) IsBoolValue

func (t Type) IsBoolValue() bool

IsBoolValue returns t == TypeBoolValue.

func (Type) IsMap

func (t Type) IsMap() bool

IsMap returns t == TypeMap.

func (Type) IsNilValue added in v0.6.0

func (t Type) IsNilValue() bool

IsNilValue returns t == TypeNilValue.

func (Type) IsNumberValue

func (t Type) IsNumberValue() bool

IsNumberValue returns t == TypeNumberValue.

func (Type) IsStringValue

func (t Type) IsStringValue() bool

IsStringValue returns t == TypeStringValue.

func (Type) IsValue

func (t Type) IsValue() bool

IsValue returns true if t is TypeStringValue or TypeBoolValue or TypeNumberValue.

type Value

type Value interface {
	Node
	String() string
	Bool() bool
	Int() int
	Int64() int64
	Float64() float64
	Compare(op Operator, v Value) bool
}

Value provides the accessor of primitive value.

type ValueQuery added in v0.2.0

type ValueQuery struct {
	Node
}

ValueQuery is a query that returns the constant value.

func (ValueQuery) Exec added in v0.2.0

func (q ValueQuery) Exec(n Node) ([]Node, error)

Exec returns the constant value.

func (ValueQuery) String added in v0.5.0

func (q ValueQuery) String() string

type ValuesQuery added in v0.8.0

type ValuesQuery struct{}

func (ValuesQuery) Exec added in v0.8.0

func (q ValuesQuery) Exec(n Node) ([]Node, error)

func (ValuesQuery) String added in v0.8.0

func (q ValuesQuery) String() string

type WalkFunc added in v0.2.0

type WalkFunc func(n Node, keys []interface{}) error

WalkFunc is the type of the function called by Walk to visit each nodes.

The keys argument contains that parent keys and the node key that type is int (array index) or string (map key).

type WalkQuery added in v0.5.0

type WalkQuery string

WalkQuery is a key of each nodes that implements methods of the Query.

func (WalkQuery) Append added in v0.5.7

func (q WalkQuery) Append(pn *Node, v Node) error

func (WalkQuery) Delete added in v0.5.7

func (q WalkQuery) Delete(pn *Node) error

func (WalkQuery) Exec added in v0.5.0

func (q WalkQuery) Exec(root Node) ([]Node, error)

Exec walks the specified root node and collects matching nodes using itself as a key.

func (WalkQuery) Set added in v0.5.7

func (q WalkQuery) Set(pn *Node, v Node) error

func (WalkQuery) String added in v0.5.0

func (q WalkQuery) String() string

Directories

Path Synopsis
cmd
tq

Jump to

Keyboard shortcuts

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