Created
March 4, 2014 17:55
-
-
Save samsalisbury/9351947 to your computer and use it in GitHub Desktop.
Easier navigation of JSON unmarshalled to interface{}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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