Categorygithub.com/icza/dyno
modulepackage
0.0.0-20230330125955-09f820a8d9c0
Repository: https://github.com/icza/dyno.git
Documentation: pkg.go.dev

# README

dyno

Build Status Go Reference Go Report Card codecov

Package dyno is a utility to work with dynamic objects at ease.

Primary goal is to easily handle dynamic objects and arrays (and a mixture of these) that are the result of unmarshaling a JSON or YAML text into an interface{} for example. When unmarshaling into interface{}, libraries usually choose either map[string]interface{} or map[interface{}]interface{} to represent objects, and []interface{} to represent arrays. Package dyno supports a mixture of these in any depth and combination.

When operating on a dynamic object, you designate a value you're interested in by specifying a path. A path is a navigation; it is a series of map keys and int slice indices that tells how to get to the value.

Should you need to marshal a dynamic object to JSON which contains maps with interface{} key type (which is not supported by encoding/json), you may use the ConvertMapI2MapS converter function.

The implementation does not use reflection at all, so performance is rather good.

Supported Operations

Example

Let's see a simple example editing a JSON text to mask out a password. This is a simplified version of the Example_jsonEdit example function:

src := `{"login":{"password":"secret","user":"bob"},"name":"cmpA"}`
var v interface{}
if err := json.Unmarshal([]byte(src), &v); err != nil {
	panic(err)
}
// Edit (mask out) password:
if err = dyno.Set(v, "xxx", "login", "password"); err != nil {
	fmt.Printf("Failed to set password: %v\n", err)
}
edited, err := json.Marshal(v)
fmt.Printf("Edited JSON: %s, error: %v\n", edited, err)

Output will be:

Edited JSON: {"login":{"password":"xxx","user":"bob"},"name":"cmpA"}, error: <nil>

# Functions

Append appends a value to a slice denoted by the path.
AppendMore appends values to a slice denoted by the path.
ConvertMapI2MapS walks the given dynamic object recursively, and converts maps with interface{} key type to maps with string key type.
Delete deletes a key from a map or an element from a slice denoted by the path.
Get returns a value denoted by the path.
GetBoolean returns a bool value denoted by the path.
GetFloat64 returns a float64 value denoted by the path.
GetFloating returns a float64 value denoted by the path.
GetInt returns an int value denoted by the path.
GetInteger returns an int64 value denoted by the path.
GetMapI returns a map with interface{} keys denoted by the path.
GetMapS returns a map with string keys denoted by the path.
GetSlice returns a slice denoted by the path.
GetString returns a string value denoted by the path.
Set sets a map or slice element denoted by the path.
SGet returns a value denoted by the path consisting of only string keys.
SSet sets a map element with string key type, denoted by the path consisting of only string keys.