Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/k0sproject/dig
A go package for working with arbitrary nested maps
https://github.com/k0sproject/dig
go json yaml
Last synced: 3 months ago
JSON representation
A go package for working with arbitrary nested maps
- Host: GitHub
- URL: https://github.com/k0sproject/dig
- Owner: k0sproject
- License: apache-2.0
- Created: 2021-02-11T14:50:45.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2024-11-12T09:20:48.000Z (3 months ago)
- Last Synced: 2024-11-12T09:34:19.044Z (3 months ago)
- Topics: go, json, yaml
- Language: Go
- Homepage:
- Size: 28.3 KB
- Stars: 5
- Watchers: 6
- Forks: 2
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Dig
A simple zero-dependency go package that provides a Ruby-like `Hash.dig` mechanism for `map[string]any`, which in YAML is refered to as "Mapping".
## Usage
The provided `dig.Mapping` is handy when unmarshaling arbitrary YAML/JSON documents.
### Example
```go
package mainimport (
"fmt""github.com/k0sproject/dig"
"gopkg.in/yaml.v2"
)var yamlDoc = []byte(`---
i18n:
hello:
se: Hejsan
fi: Moi
world:
se: Värld
fi: Maailma
`)func main() {
m := dig.Mapping{}
if err := yaml.Unmarshal(yamlDoc, &m); err != nil {
panic(err)
}// You can use DigMapping to access a deeply nested map and set values.
// Any missing Mapping level in between will be created.
m.DigMapping("i18n", "hello")["es"] = "Hola"
m.DigMapping("i18n", "world")["es"] = "Mundo"langs := []string{"fi", "se", "es"}
for _, l := range langs {// You can use Dig to access a deeply nested value
greeting := m.Dig("i18n", "hello", l).(string)// ..or DigString to avoid having to cast it to string.
target := m.DigString("i18n", "world", l)fmt.Printf("%s, %s!\n", greeting, target)
}
}
```Output:
```
Moi, Maailma!
Hejsan, Värld!
Hola, Mundo!
```