https://github.com/mnogu/go-dig
Go version of Hash#dig and Array#dig in Ruby
https://github.com/mnogu/go-dig
array dig go hash json ruby
Last synced: 29 days ago
JSON representation
Go version of Hash#dig and Array#dig in Ruby
- Host: GitHub
- URL: https://github.com/mnogu/go-dig
- Owner: mnogu
- License: mit
- Created: 2020-08-29T01:50:56.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2022-05-31T23:52:41.000Z (over 3 years ago)
- Last Synced: 2025-01-17T16:37:46.133Z (12 months ago)
- Topics: array, dig, go, hash, json, ruby
- Language: Go
- Homepage:
- Size: 11.7 KB
- Stars: 1
- Watchers: 3
- Forks: 1
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-dig
[](https://pkg.go.dev/mod/github.com/mnogu/go-dig)
[](https://github.com/mnogu/go-dig/actions?query=workflow%3AGo)
Go version of [`Hash#dig`](https://docs.ruby-lang.org/en/2.7.0/Hash.html#method-i-dig) and [`Array#dig`](https://docs.ruby-lang.org/en/2.7.0/Array.html#method-i-dig) in Ruby
## Download and Install
```
$ go get -u github.com/mnogu/go-dig
```
## Examples
```go
package main
import (
"encoding/json"
"fmt"
"github.com/mnogu/go-dig"
)
func main() {
var jsonBlob = []byte(`{"foo": {"bar": {"baz": 1}}}`)
var v interface{}
if err := json.Unmarshal(jsonBlob, &v); err != nil {
fmt.Println(err)
}
success, err := dig.Dig(v, "foo", "bar", "baz")
if err != nil {
fmt.Println(err)
}
// foo.bar.baz = 1
fmt.Println("foo.bar.baz =", success)
failure, err := dig.Dig(v, "foo", "qux", "quux")
if err != nil {
// key qux not found in
fmt.Println(err)
}
// foo.qux.quux =
fmt.Println("foo.qux.quux =", failure)
}
```
```go
package main
import (
"encoding/json"
"fmt"
"github.com/mnogu/go-dig"
)
func main() {
var jsonBlob = []byte(`{"foo": [10, 11, 12]}`)
var v interface{}
if err := json.Unmarshal(jsonBlob, &v); err != nil {
fmt.Println(err)
}
success, err := dig.Dig(v, "foo", 1)
if err != nil {
fmt.Println(err)
}
// foo.1 = 11
fmt.Println("foo.1 =", success)
failure, err := dig.Dig(v, "foo", 1, 0)
if err != nil {
// 11 isn't a slice
fmt.Println(err)
}
// foo.1.0 =
fmt.Println("foo.1.0 =", failure)
failure2, err := dig.Dig(v, "foo", "bar")
if err != nil {
// [10 11 12] isn't a map
fmt.Println(err)
}
// foo.bar =
fmt.Println("foo.bar =", failure2)
}
```