mappath

package module
v0.0.0-...-900695c Latest Latest
Warning

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

Go to latest
Published: May 5, 2015 License: ISC Imports: 6 Imported by: 2

README

Build Status

MapPath

Go library for convenient read-access to data structures.

Purpose and Scope

This is not an XPATH implementation for Go, but a simple path interface to structured data files, like JSON or YAML. Think accessing configuration files or the like.

API Changes

v1 -> v2
  • Removed the "Get" prefix of all methods, so former mappath.GetInt("foo") becomes mappath.Int("foo"). The outlier is GetSub which is now Child.
  • Added Value-getter with scalar response, eg mappath.IntV("foo") has the return signatur of int, while mappath.Int("foo") still has (int, error). The V-getter return the nil value, on error

Documentation

GoDoc can be found here

Installation
$ go get gopkg.in/ukautz/mappath.v2
Usage

This package needs at least Go 1.1. Import package with

import "gopkg.in/ukautz/mappath.v2"

Then you can do

mp, err := mappath.FromJsonFile("path/to.json")
if err != nil {
    panic(err)
}

str, err := mp.GetString("foo/bar/0/hello")

The above assumes a simple JSON file:

{
    "foo": {
        "bar": [
            {
                "hello": "world"
            }
        ]
    }
}
Intialization

The library works on map[string]interface{} structures. Those can come from JSON/YAML files or anywhere else. The above example illustrates how to get easily started with an existing JSON file. Here is how you do it Go-only:

mp := mappath.NewMapPath(map[string]interface{}{
    "foo": map[string]interface{}{
        "bar": map[string]interface{}{
            "baz": "hello",
        },
    },
})
v, _ := mp.GetString("foo/bar/baz")
fmt.Printf("Say %s world\n", v)
Accessing data
mp := mappath.NewMapPath(source)

// get an interface{}
result, err := mp.Get("the/path")

// get an int value
// assumes a structure like: {"the":{"path":123}}
result, err = mp.GetInt("the/path")

// get an array of int values
// assumes a structure like: {"the":{"path":[123, 234]}}
result, err = mp.GetInts("the/path")

// get a float value
// assumes a structure like: {"the":{"path":123.1}}
result, err = mp.GetFloat("the/path")

// get an array float values
// assumes a structure like: {"the":{"path":[123.1, 234.9]}}
result, err = mp.GetFloats("the/path")

// get a string value
// assumes a structure like: {"the":{"path":"foo"}}
result, err = mp.GetString("the/path")

// get an array of string values
// assumes a structure like: {"the":{"path":["foo","bar"}}
result, err = mp.GetStrings("the/path")

// get a map value
// assumes a structure like: {"the":{"path":{"foo":"bar"}}
result, err = mp.GetMap("the/path")

// get an array of map values
// assumes a structure like: {"the":{"path":[{"foo":"bar1"},{"foo":"bar2"}]}
result, err = mp.GetMaps("the/path")
Using sub structures

For example, when iterating a structure like the following

{
    "users":[
        {
            "name":"Cpt Kirk"
        },
        {
            "name":"Mr Spock"
        },
        {
            "name":"Jean-Luc"
        }
    ]
}

Here is how you can conveniently access the nested maps:

subs, err := mp.GetSubs("users")
for _, user := range subs {
    fmt.Printf("Say hello to %s\n", user.GetString("name"))
}
Error handling

mappath.NotFoundError

Returned if the accessed path does not exist. The result will contain the appropriate nil value.

mappath.InvalidTypeError

Returned if you get a path which exists but contains a value which can neither be converted nor parsed. For example: trying to get the int value of the string foo bar.

mappath.UnsupportedTypeError

Returned on array getter. The currently supported types are: int, float64, string and map[string]interface{}.

Convenience: Fallback values

Since I developed this library mainly for working with complex configuration files it's a common use-case to provide a fallback value, which is used if nothing is found at the given path. If you provide a fallback value, than no NotFoundError will be returned.

// returns "Some Fallback" if the path does not exist
result, err := mp.GetString("the/path", "Some Fallback")

See also

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Branch

type Branch map[string]interface{}

Branch is a shorthand for the map-string structures we're working with

type InvalidTypeError

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

InvalidTypeError is returned if a type getter (eg GetInt) is used but the found type cannot be converted

func (*InvalidTypeError) Error

func (err *InvalidTypeError) Error() string

type MapPath

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

MapPath is the primary object type this package is about

func FromJson

func FromJson(in []byte) (*MapPath, error)

FromJson is a factory method to create a MapPath from JSON byte data

func FromJsonFile

func FromJsonFile(file string) (*MapPath, error)

FromJsonFile is a factory method to create a MapPath from a JSON file

func NewMapPath

func NewMapPath(root map[string]interface{}) *MapPath

NewMapPath creates is the primary constructor

func (*MapPath) Array

func (this *MapPath) Array(refType reflect.Type, path string) (interface{}, bool, error)

GetArray returns nested array of provided type. Fallback values are not supported. If the path value is not an array then an InvalidTypeError is returned. You should use the specialized methods (GetInts, GetStrings..) unless you know what you are doing.

func (*MapPath) Bool

func (this *MapPath) Bool(path string, fallback ...bool) (bool, error)

GetInt returns int value of path. If value cannot be parsed or converted then an InvalidTypeError is returned

func (*MapPath) BoolV

func (this *MapPath) BoolV(path string, fallback ...bool) bool

GetBoolV returns bool value of path. If value cannot be parsed or converted then fallback or false is returned. Handy in single value context.

func (*MapPath) Child

func (this *MapPath) Child(path string, fallback ...*MapPath) (*MapPath, error)

GetSub return a new MapPath object representing the sub structure, which needs to be a map. If the sub structure is of any other type then an InvalidTypeError is returned

func (*MapPath) ChildV

func (this *MapPath) ChildV(path string, fallback ...*MapPath) *MapPath

GetMapV returns *MapPath value of path. If value cannot be parsed or converted then fallback or nil is returned. Handy in single value context.

func (*MapPath) Childs

func (this *MapPath) Childs(path string, fallback ...[]*MapPath) ([]*MapPath, error)

GetSubs returns a nested array of sub structures. If the path value is not an array of maps then an InvalidTypeError is returned.

func (*MapPath) ChildsV

func (this *MapPath) ChildsV(path string, fallback ...[]*MapPath) []*MapPath

GetSubsV returns []*MapPath value of path. If value cannot be parsed or converted then fallback or nil is returned. Handy in single value context.

func (*MapPath) Float

func (this *MapPath) Float(path string, fallback ...float64) (float64, error)

GetFloat returns float64 value of path. If value cannot be parsed or converted then an InvalidTypeError is returned

func (*MapPath) FloatV

func (this *MapPath) FloatV(path string, fallback ...float64) float64

GetFloatV returns float64 value of path. If value cannot be parsed or converted then fallback or 0.0 is returned. Handy in single value context.

func (*MapPath) Floats

func (this *MapPath) Floats(path string, fallback ...[]float64) ([]float64, error)

GetFloats returns an array of float64 values. Tries to convert (eg int) or parse (string) values. If the path value cannot be parsed or converted than an InvalidTypeError is returned.

func (*MapPath) FloatsV

func (this *MapPath) FloatsV(path string, fallback ...[]float64) []float64

GetFloatsV returns []float64 value of path. If value cannot be parsed or converted then fallback or nil is returned. Handy in single value context.

func (*MapPath) Get

func (this *MapPath) Get(path string, fallback ...interface{}) (interface{}, error)

Get returns object found with given path

func (*MapPath) GetAs

func (this *MapPath) GetAs(path string, typ reflect.Type, fallback ...interface{}) (interface{}, error)

func (*MapPath) Has

func (this *MapPath) Has(path string) bool

Has check whether the given path exists

func (*MapPath) Int

func (this *MapPath) Int(path string, fallback ...int) (int, error)

GetInt returns int value of path. If value cannot be parsed or converted then an InvalidTypeError is returned

func (*MapPath) IntV

func (this *MapPath) IntV(path string, fallback ...int) int

GetIntV returns int value of path. If value cannot be parsed or converted then fallback or 0 is returned. Handy in single value context.

func (*MapPath) Ints

func (this *MapPath) Ints(path string, fallback ...[]int) ([]int, error)

GetInts returns an array of int values. Tries to convert (eg float) or parse (string) values. If the path value cannot be parsed or converted than an InvalidTypeError is returned.

func (*MapPath) IntsV

func (this *MapPath) IntsV(path string, fallback ...[]int) []int

GetIntsV returns []int value of path. If value cannot be parsed or converted then fallback or nil is returned. Handy in single value context.

func (*MapPath) Map

func (this *MapPath) Map(path string, fallback ...map[string]interface{}) (map[string]interface{}, error)

GetMap returns the map value of path. If value is not a map then an InvalidTypeError is returned

func (*MapPath) MapV

func (this *MapPath) MapV(path string, fallback ...map[string]interface{}) map[string]interface{}

GetMapV returns map[string]interface{} value of path. If value cannot be parsed or converted then fallback or nil is returned. Handy in single value context.

func (*MapPath) Maps

func (this *MapPath) Maps(path string, fallback ...[]map[string]interface{}) ([]map[string]interface{}, error)

GetMaps returns a nested array of maps. If the path value is not an array of maps then an InvalidTypeError is returned.

func (*MapPath) MapsV

func (this *MapPath) MapsV(path string, fallback ...[]map[string]interface{}) []map[string]interface{}

GetMapsV returns []map[string]interface{} value of path. If value cannot be parsed or converted then fallback or nil is returned. Handy in single value context.

func (*MapPath) Root

func (this *MapPath) Root() map[string]interface{}

Root returns underly root map

func (*MapPath) String

func (this *MapPath) String(path string, fallback ...string) (string, error)

GetString returns string value of path. If value cannot be converted then an InvalidTypeError is returned

func (*MapPath) StringV

func (this *MapPath) StringV(path string, fallback ...string) string

GetStringV returns string value of path. If value cannot be parsed or converted then fallback or "" is returned. Handy in single value context.

func (*MapPath) Strings

func (this *MapPath) Strings(path string, fallback ...[]string) ([]string, error)

GetStrings returns an array of string values. If the path value is incomaptible (eg map array) then an InvalidTypeError is returned

func (*MapPath) StringsV

func (this *MapPath) StringsV(path string, fallback ...[]string) []string

GetStringsV returns []string value of path. If value cannot be parsed or converted then fallback or nil is returned. Handy in single value context.

type NotFoundError

type NotFoundError string

NotFoundError is returned if a given path cannot be found

func (NotFoundError) Error

func (err NotFoundError) Error() string

type UnsupportedTypeError

type UnsupportedTypeError string

UnsupportedTypeError is returned if an unsupported type is used

func (UnsupportedTypeError) Error

func (err UnsupportedTypeError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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