object

package module
v0.0.0-...-d94269f Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2022 License: MIT Imports: 8 Imported by: 0

README

Go documentation GitHub go.mod Go version

📦 Object

Tool to work through unspecified-scheme objects (like unmarshalled json, yaml, etc.)

❤️ Need in Your Feedback! Together we'll make a better tool!
Please, make an issue or PR if you found inconsistent behavior, errors or missed test-cases. Or just leave a comment at gitter for new feature request.

Sometimes, we can't guess a scheme for some serialized object. By the way, we can't describe the scheme in Go structures. But we have to work with the unknown object. And, here is several ways to solve this trouble:

  • Make a partial-filled structures for known part of the object. Of course, it isn't common way for all cases. Especially, for cases that require some dynamics in behavior or when some field can have different type for different cases.
  • Unmarshal the object into interface{} and work with them via type-casting or use reflection. This is a hard way with tons of code. Usually, nobody understands how it works and what happens. Even the developer of this part of code after time.

This tool tries to help. It is inspired by JavaScript and their API to manipulate objects.

Goal is to make very comfortable tool.

⚙️ Install

go get -u github.com/the-go-tool/object

📚 Usage

If you familiar with JavaScript, you already familiar with this tool's methods. Most of these methods constructed to work in chain-mode.

🚧 It's a draft. Actually, this module isn't ready.

A bit of code to start:

package main

import (
	"encoding/json"
	"github.com/the-go-tool/object"
)

func main() {
	source := []byte(`{"a":{"b":"c","d":-500.5},"e":[3, 2, 1]}`)
	var data interface{}
	_ = json.Unmarshal(source, &data)
	
	obj := object.New(data)
	
	obj.Get("a").Get("b").String() // "c"
	obj.GetIndex(1).Json() // "[3, 2, 3]" - getting keys by index and json marshaling
	obj.Get("e").GetIndex(0).String() // "3" - auto-convert if possible
	obj.Get("e").Get("0").Int() // 3 - same as above alternative
	
	obj.Get("not-exists").Get("d").IsExists() // false
	obj.Get("not-exists").Get("d").IsNull() // false - because it's not exists
	obj.Get("not-exists").Get("d").IsEmpty() // false - because it's not exists
	obj.Get("not-exists").Get("d").String() // "" - empty string, no error
	
	obj.Get("a").Get("d").IsValid() // true - exists & not null & not empty
	obj.Get("a").Get("d").IsNumber() // true - int, uint, int64, and etc allowed
	obj.Get("a").Get("d").Float64() // -500.5
	obj.Get("a").Get("d").Uint8() // 12
	
	obj.Get("a").Keys() // ["b", "d"]
	obj.Get("a").Get("b").Values() // [Object("c"), Object(-500.5)]
	obj.Get("a").Get("b").Entries() // [{Key: Object("b"), Value: Object("c")}, ...]
	
	obj.GetPath("e[1]").Int() // 2 - JavaScript-like syntax
	
	// ==========
	
	// JOQL syntax. JavaScript Object Query Language:
	yes := object.NewFromData(source).Path(`a.b[5].c["data"].d`).ToBool()
}

Documentation

Index

Examples

Constants

View Source
const (
	ErrorObjectNotExists = "object isn't exists"
	ErrorTypeNotSupport  = "type isn't supporting"
	ErrorFieldNotFound   = "field name not found"
	ErrorIndexParse      = "index can't be parsed"
	ErrorIndexRange      = "index out of range"
	ErrorDataParse       = "data can't be parsed"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Entry

type Entry struct {
	Key   string
	Value Object
}

Entry - object that represents a key-value pair for such methods like GetEntries, ForEach, Map, etc.

type Error

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

Error - objects manipulation error

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Object

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

Object - type of anything.

func New

func New(obj interface{}) Object

New - create new object from any type.

func NewFromBson

func NewFromBson(data []byte) Object

NewFromBson - create new object from bson bytes

func NewFromData

func NewFromData(data []byte) Object

NewFromData - detect and create object from any supporting data format. It's supports JSON, YAML, TOML and BSON. XML and HTML isn't supporting, so it has extra fields which isn't straight data containers (like tags and attrs). Use your favourite XML/HTML deserializer and pass the result to New.

func NewFromJson

func NewFromJson(data []byte) Object

NewFromJson - create new object from json bytes

func NewFromToml

func NewFromToml(data []byte) Object

NewFromToml - create new object from toml bytes

func NewFromValue

func NewFromValue(val reflect.Value) Object

NewFromValue - create new object from reflect.Value

func NewFromYaml

func NewFromYaml(data []byte) Object

NewFromYaml - create new object from yaml bytes

func (Object) Get

func (o Object) Get(key string) Object

Get - get sub-object by their key-name. Can be applied to reflect.Map and reflect.Slice kinds. Acts like GetIndex if Object is reflect.Slice.

Example
//source := `{
//	"a": "value",
//	"b": {
//		"c": -500.5
//	},
//	"d": [3, 2, 1]
//}`
//var document interface{}
//_ = json.Unmarshal([]byte(source), &document)
//object := New(document)
//
//object.Get("a").String() // "value"
Output:

func (Object) GetEntries

func (o Object) GetEntries() []Entry

GetEntries - get key-values of reflect.Map or reflect.Slice. For reflect.Map order of entries is not guaranteeing.

func (Object) GetError

func (o Object) GetError() error

GetError - last operation error info.

func (Object) GetIndex

func (o Object) GetIndex(index int) Object

GetIndex - get sub-object by their index in slice.

func (Object) GetKeys

func (o Object) GetKeys() []string

GetKeys - get keys names of reflect.Map or indexes for reflect.Slice. For reflect.Map order of keys is not guaranteeing.

func (Object) GetValues

func (o Object) GetValues() []Object

GetValues - get values of reflect.Map or reflect.Slice. For reflect.Map order of values is not guaranteeing.

func (Object) IsBool

func (o Object) IsBool() bool

IsBool - check that the object is boolean or can be cast. For string truthy values are: "true", "yes", "on" and if it can be cast to number - any except zero. For numbers truthy values any except zero. TODO: Make the realisation and tests

func (Object) IsBoolStrict

func (o Object) IsBoolStrict() bool

IsBoolStrict - check that the object is boolean.

func (Object) IsEmpty

func (o Object) IsEmpty() bool

IsEmpty - check that the object value empty. reflect.Array isn't contain any elements and reflect.Struct isn't contain any fields. Other types is equal their default values.

func (Object) IsExists

func (o Object) IsExists() bool

IsExists - check that the object exists.

func (Object) IsFloat

func (o Object) IsFloat() bool

IsFloat - check that the object is float or can be cast.

func (Object) IsFloatStrict

func (o Object) IsFloatStrict() bool

IsFloatStrict - check that the object is float number.

func (Object) IsInt

func (o Object) IsInt() bool

IsInt - check that the object is integer or can be cast lossless.

func (Object) IsIntStrict

func (o Object) IsIntStrict() bool

IsIntStrict - check that the object is integer number.

func (Object) IsMap

func (o Object) IsMap() bool

IsMap - check that the object value is map.

func (Object) IsNil

func (o Object) IsNil() bool

IsNil - check that the object value is nil/null.

func (Object) IsSlice

func (o Object) IsSlice() bool

IsSlice - check that the object value is slice.

func (Object) IsString

func (o Object) IsString() bool

IsString - check that the object is string or can be cast. Simple types like numbers always can be cast. If you would like to get something more complicated - use ToJson or similar serialization. If the required type serialization isn't presented - use ToValue and pass it to your favourite serializer manually.

func (Object) IsStringStrict

func (o Object) IsStringStrict() bool

IsStringStrict - check that the object is string.

Jump to

Keyboard shortcuts

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