Skip to content

Instantly share code, notes, and snippets.

@samsalisbury
Created March 4, 2014 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsalisbury/9351947 to your computer and use it in GitHub Desktop.
Save samsalisbury/9351947 to your computer and use it in GitHub Desktop.
Easier navigation of JSON unmarshalled to interface{}
package main
/*
Allows <d>easier</d> inelegant navigation of JSON unmarshalled to interface{}
*/
type si struct {
value interface{}
}
func NewSi(value interface{}) si {
return si{value: value}
}
func (thing si) m() map[string]si {
natural := thing.value.(map[string]interface{})
m := make(map[string]si, len(natural))
for k, v := range natural {
m[k] = NewSi(v)
}
return m
}
func (thing si) a() []si {
natural := thing.value.([]interface{})
a := make([]si, len(natural))
for k, v := range natural {
a[k] = NewSi(v)
}
return a
}
/*
Allows you to write this type of monstrosity:
func main() {
//... (set responseBody to a []byte containing valid JSON)
var container interface{}
err := json.Unmarshal(responseBody, &container)
result := findSomething()
fmt.Printf("Found: %v", *result)
}
func findSomething() *string {
for k1, v := range NewSi(container).m() {
if k1 == "interestingKey" {
for k2, v2 := range v.m() {
if k2 == "interestingSubKey" {
for _, v3 := range v2.a() {
val := v3.m()["iKnowThisKeyExists"].m()["andThisOne"].value.(string)
return &val
}
}
}
}
}
return nil
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment