typed

package module
v1.1.8 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2022 License: MIT Imports: 8 Imported by: 40

README

Typed

Making map[string]interface{} slightly less painful

It isn't always desirable or even possible to decode JSON into a structure. That, unfortunately, leaves us with writing ugly code around map[string]interface{} and []interace{}.

This library hopes to make that slightly less painful.

Install

go get github.com/karlseguin/typed

Note

While the library could be used with any map[string]interface{}, it is tailored to be used with encoding/json. Specifically, it won't ever try to convert data, except for integers (which encoding/json treats as floats).

Usage:

A typed wrapper around a map[string]interface{} can be created in one of three ways:

// directly from a map[string]interace{}
typed := typed.New(a_map)

// from a json []byte
typed, err := typed.Json(data)

// from a file containing JSON
typed, err := typed.JsonFile(path)

Once we have a typed wrapper, we can use various functions to navigate the structure:

  • Bool(key string) bool

  • Int(key string) int

  • Float(key string) float64

  • String(key string) string

  • Object(key string) typed.Type

  • Interface(key string) interface{}

  • BoolOr(key string, defaultValue bool) bool

  • IntOr(key string, defaultValue int) int

  • FloatOr(key string, defaultValue float64) float64

  • StringOr(key string, defaultValue string) string

  • ObjectOr(key string, defaultValue map[string]interface{}) typed.Type

  • InterfaceOr(key string, defaultValue interface{}) interface{}

  • BoolMust(key string) bool

  • IntMust(key string) int

  • FloatMust(key string) float

  • StringMust(key string) string

  • ObjectMust(key string) typed.Type

  • `InterfaceMust(key string) interface{}``

  • BoolIf(key string) (bool, bool)

  • IntIf(key string) (int, bool)

  • FloatIf(key string) (float, bool)

  • StringIf(key string) (string, bool)

  • ObjectIf(key string) (typed.Type, bool)

  • InterfaceIf(key string) (interface{}, bool)

We can also extract arrays via:

  • Bools(key string) []bool
  • Ints(key string) []int
  • Ints64(key string) []int64
  • Floats(key string) []float64
  • Strings(key string) []string
  • StringsOr(key string, defaultValue []string) []string
  • BoolsOr(key string, defaultValue []bool) []bool
  • IntsOr(key string, defaultValue []int) []int
  • Ints64Or(key string, defaultValue []int64) []int64
  • FloatsOr(key string, defaultValue []float64) []float64

We can extract nested objects, other as another typed wrapper, or as a raw map[string]interface{}:

  • Object(key string) Typed

  • ObjectOr(key string, map[string]interface) Typed

  • ObjectIf(key string) (Typed, bool)

  • Objects(key string) []Typed

  • Map(key string) map[string]interface{}

  • MaoOr(key string, map[string]interface) map[string]interface{}

  • MapIf(key string) (map[string]interface{}, bool)

  • Maps(key string) []map[string]interface{}

We can extract key value pairs:

  • StringBool(key string) map[string]bool
  • StringInt(key string) map[string]int
  • StringFloat(key string) map[string]float64
  • StringString(key string) map[string]string
  • StringObject(key string) map[string]Typed

Example

package main

import (
  "fmt"
  "typed"
)

func main() {
  json := `
{
  "log": true,
  "name": "leto",
  "percentiles": [75, 85, 95],
  "server": {
    "port": 9001,
    "host": "localhost"
  },
  "cache": {
    "users": {"ttl": 5}
  },
  "blocked": {
    "10.10.1.1": true
  }
}`
  typed, err := typed.JsonString(json)
  if err != nil {
    fmt.Println(err)
  }

  fmt.Println(typed.Bool("log"))
  fmt.Println(typed.String("name"))
  fmt.Println(typed.Ints("percentiles"))
  fmt.Println(typed.FloatOr("load", 0.5))

  server := typed.Object("server")
  fmt.Println(server.Int("port"))
  fmt.Println(server.String("host"))

  fmt.Println(typed.Map("server"))

  fmt.Println(typed.StringObject("cache")["users"].Int("ttl"))
  fmt.Println(typed.StringBool("blocked")["10.10.1.1"])
}

Misc

To Bytes

ToBytes(key string) ([]byte, error) can be used to get the JSON data, as a []byte, from the Type. KeyNotFound will be returned if the key isn't valid.

Alternatively, MustBytes(key string) []byte can be used. It will panic on error.

Root Array

Support for JSON document with arrays at their root is supported. Use the JsonArray(data []byte), JsonStringArray(data string) and JsonFileArray(path string) to receive an []Typed

If the array has primitive values, the syntax is a little awkward. The key for the field is "0":

json := `[1, {"name": "leto"}, "spice"]`

typed, err := typed, err := typed.JsonStringArray(json)
if err != nil {
  panic(err)
}
println(typed[0].Int("0"))
println(typed[1].String("name"))
println(typed[2].String("0"))

JsonWriter

The JsonWriter library provides the opposite functionality: a lightweight approaching to writing JSON data.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Used by ToBytes to indicate that the key was not
	// present in the type
	KeyNotFound = errors.New("Key not found")
	Empty       = Typed(nil)
)

Functions

This section is empty.

Types

type Typed

type Typed map[string]interface{}

A Typed type helper for accessing a map

func Json

func Json(data []byte) (Typed, error)

Create a Typed helper from the given JSON bytes

func JsonArray

func JsonArray(data []byte) ([]Typed, error)

Create an array of Typed helpers Used for when the root is an array which contains objects

func JsonFile

func JsonFile(path string) (Typed, error)

Create a Typed helper from the JSON within a file

func JsonFileArray

func JsonFileArray(path string) ([]Typed, error)

Create an array of Typed helpers from a file Used for when the root is an array which contains objects

func JsonReader

func JsonReader(reader io.Reader) (Typed, error)

Create a Typed helper from the given JSON stream

func JsonReaderArray

func JsonReaderArray(reader io.Reader) ([]Typed, error)

Create an array of Typed helpers given JSON stream

func JsonString

func JsonString(data string) (Typed, error)

Create a Typed helper from the given JSON string

func JsonStringArray

func JsonStringArray(data string) ([]Typed, error)

Create an array of Typed helpers from a string Used for when the root is an array which contains objects

func Must

func Must(data []byte) Typed

Create a Typed helper from the given JSON bytes, panics on error

func New

func New(m map[string]interface{}) Typed

Wrap the map into a Typed

func (Typed) Bool

func (t Typed) Bool(key string) bool

Returns a boolean at the key, or false if it doesn't exist, or if it isn't a bool

func (Typed) BoolIf

func (t Typed) BoolIf(key string) (bool, bool)

Returns a boolean at the key and whether or not the key existed and the value was a bolean

func (Typed) BoolMust

func (t Typed) BoolMust(key string) bool

Returns a bool or panics

func (Typed) BoolOr

func (t Typed) BoolOr(key string, d bool) bool

Returns a boolean at the key, or the specified value if it doesn't exist or isn't a bool

func (Typed) Bools

func (t Typed) Bools(key string) []bool

Returns an slice of boolean, or an nil slice

func (Typed) BoolsIf

func (t Typed) BoolsIf(key string) ([]bool, bool)

Returns a boolean slice + true if valid Returns nil + false otherwise (returns nil+false if one of the values is not a valid boolean)

func (Typed) BoolsOr

func (t Typed) BoolsOr(key string, d []bool) []bool

Returns an slice of boolean, or the specified slice

func (Typed) Exists

func (t Typed) Exists(key string) bool

func (Typed) Float

func (t Typed) Float(key string) float64

func (Typed) FloatIf

func (t Typed) FloatIf(key string) (float64, bool)

Returns an float at the key and whether or not the key existed and the value was an float

func (Typed) FloatMust

func (t Typed) FloatMust(key string) float64

Returns an float or panics

func (Typed) FloatOr

func (t Typed) FloatOr(key string, d float64) float64

Returns a float at the key, or the specified value if it doesn't exist or isn't a float

func (Typed) Floats

func (t Typed) Floats(key string) []float64

Returns an slice of floats, or a nil slice

func (Typed) FloatsIf

func (t Typed) FloatsIf(key string) ([]float64, bool)

Returns a float slice + true if valid Returns nil + false otherwise (returns nil+false if one of the values is not a valid float)

func (Typed) FloatsOr

func (t Typed) FloatsOr(key string, d []float64) []float64

Returns an slice of floats, or the specified slice if the key doesn't exist or isn't a valid []float64

func (Typed) Int

func (t Typed) Int(key string) int

func (Typed) IntIf

func (t Typed) IntIf(key string) (int, bool)

Returns an int at the key and whether or not the key existed and the value was an int

func (Typed) IntMust

func (t Typed) IntMust(key string) int

Returns an int or panics

func (Typed) IntOr

func (t Typed) IntOr(key string, d int) int

Returns a int at the key, or the specified value if it doesn't exist or isn't a int

func (Typed) Interface

func (t Typed) Interface(key string) interface{}

func (Typed) InterfaceIf

func (t Typed) InterfaceIf(key string) (interface{}, bool)

Returns an string at the key and whether or not the key existed and the value was an string

func (Typed) InterfaceMust

func (t Typed) InterfaceMust(key string) interface{}

Returns an interface or panics

func (Typed) InterfaceOr

func (t Typed) InterfaceOr(key string, d interface{}) interface{}

Returns a string at the key, or the specified value if it doesn't exist or isn't a strin

func (Typed) Ints

func (t Typed) Ints(key string) []int

Returns an slice of ints, or the specified slice Some conversion is done to handle the fact that JSON ints are represented as floats.

func (Typed) Ints64

func (t Typed) Ints64(key string) []int64

Returns an slice of ints64, or the specified slice Some conversion is done to handle the fact that JSON ints are represented as floats.

func (Typed) Ints64If

func (t Typed) Ints64If(key string) ([]int64, bool)

Returns a boolean slice + true if valid Returns nil + false otherwise (returns nil+false if one of the values is not a valid boolean)

func (Typed) Ints64Or

func (t Typed) Ints64Or(key string, d []int64) []int64

Returns an slice of ints, or the specified slice if the key doesn't exist or isn't a valid []int. Some conversion is done to handle the fact that JSON ints are represented as floats.

func (Typed) IntsIf

func (t Typed) IntsIf(key string) ([]int, bool)

Returns a int slice + true if valid Returns nil + false otherwise (returns nil+false if one of the values is not a valid int)

func (Typed) IntsOr

func (t Typed) IntsOr(key string, d []int) []int

Returns an slice of ints, or the specified slice if the key doesn't exist or isn't a valid []int. Some conversion is done to handle the fact that JSON ints are represented as floats.

func (Typed) Keys

func (t Typed) Keys() []string

func (Typed) Map

func (t Typed) Map(key string) map[string]interface{}

Returns a map[string]interface{} at the key or a nil map if the key doesn't exist or if the key isn't a map[string]interface

func (Typed) MapIf

func (t Typed) MapIf(key string) (map[string]interface{}, bool)

Returns a map[string]interface at the key and whether or not the key existed and the value was an map[string]interface{}

func (Typed) MapOr

func (t Typed) MapOr(key string, d map[string]interface{}) map[string]interface{}

Returns a map[string]interface{} at the key or the specified default if the key doesn't exist or if the key isn't a map[string]interface

func (Typed) Maps

func (t Typed) Maps(key string) []map[string]interface{}

Returns an slice of map[string]interfaces, or a nil slice

func (Typed) MustBytes

func (t Typed) MustBytes(key string) []byte

func (Typed) Object

func (t Typed) Object(key string) Typed

Returns a Typed helper at the key If the key doesn't exist, a default Typed helper is returned (which will return default values for any subsequent sub queries)

func (Typed) ObjectIf

func (t Typed) ObjectIf(key string) (Typed, bool)

Returns a Typed helper at the key and whether or not the key existed and the value was an map[string]interface{}

func (Typed) ObjectMust

func (t Typed) ObjectMust(key string) Typed

Returns an typed object or panics

func (Typed) ObjectOr

func (t Typed) ObjectOr(key string, d map[string]interface{}) Typed

Returns a Typed helper at the key or the specified default if the key doesn't exist or if the key isn't a map[string]interface{}

func (Typed) Objects

func (t Typed) Objects(key string) []Typed

Returns an slice of Typed helpers, or a nil slice

func (Typed) ObjectsIf

func (t Typed) ObjectsIf(key string) ([]Typed, bool)

Returns a slice of Typed helpers and true if exists, otherwise; nil and false.

func (Typed) ObjectsMust

func (t Typed) ObjectsMust(key string) []Typed

func (Typed) String

func (t Typed) String(key string) string

func (Typed) StringBool

func (t Typed) StringBool(key string) map[string]bool

Returns an map[string]bool

func (Typed) StringFloat

func (t Typed) StringFloat(key string) map[string]float64

Returns an map[string]float64

func (Typed) StringIf

func (t Typed) StringIf(key string) (string, bool)

Returns an string at the key and whether or not the key existed and the value was an string

func (Typed) StringInt

func (t Typed) StringInt(key string) map[string]int

Returns an map[string]int Some work is done to handle the fact that JSON ints are represented as floats.

func (Typed) StringMust

func (t Typed) StringMust(key string) string

Returns an string or panics

func (Typed) StringObject

func (t Typed) StringObject(key string) map[string]Typed

Returns an map[string]Typed

func (Typed) StringOr

func (t Typed) StringOr(key string, d string) string

Returns a string at the key, or the specified value if it doesn't exist or isn't a string

func (Typed) StringString

func (t Typed) StringString(key string) map[string]string

Returns an map[string]string

func (Typed) Strings

func (t Typed) Strings(key string) []string

Returns an slice of strings, or a nil slice

func (Typed) StringsIf

func (t Typed) StringsIf(key string) ([]string, bool)

Returns a string slice + true if valid Returns nil + false otherwise (returns nil+false if one of the values is not a valid string)

func (Typed) StringsOr

func (t Typed) StringsOr(key string, d []string) []string

Returns an slice of strings, or the specified slice if the key doesn't exist or isn't a valid []string

func (Typed) Time

func (t Typed) Time(key string) time.Time

func (Typed) TimeIf

func (t Typed) TimeIf(key string) (time.Time, bool)

Returns an time.time at the key and whether or not the key existed and the value was a time.Time

func (Typed) TimeMust

func (t Typed) TimeMust(key string) time.Time

Returns a time.Time or panics

func (Typed) TimeOr

func (t Typed) TimeOr(key string, d time.Time) time.Time

Returns a time at the key, or the specified value if it doesn't exist or isn't a time

func (Typed) ToBytes

func (t Typed) ToBytes(key string) ([]byte, error)

Marhals the type into a []byte. If key isn't valid, KeyNotFound is returned. If the typed doesn't represent valid JSON, a relevant JSON error is returned

Jump to

Keyboard shortcuts

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