Skip to content

Instantly share code, notes, and snippets.

@binary132
Created June 3, 2014 16:06
Show Gist options
  • Save binary132/bd2e75df732417ebdf84 to your computer and use it in GitHub Desktop.
Save binary132/bd2e75df732417ebdf84 to your computer and use it in GitHub Desktop.
Strip a nested map[interface{}]interface{} down to a nested map[string]interface{}
package main
import (
"errors"
"fmt"
"labix.org/v2/mgo/bson"
)
func main() {
vals := &map[string]interface{}{
"values": map[string]interface{}{
"foo": map[interface{}]interface{}{
"dead": "feeb",
"beef": "daed"},
"bar": "baz"}}
data, err := bson.Marshal(vals)
if err != nil {
panic(err)
}
fmt.Printf("%q\n\n", data)
err = stepIn(*vals)
if err != nil {
panic(err)
}
data, err = bson.Marshal(vals)
if err != nil {
panic(err)
}
fmt.Printf("%q\n\n", data)
//var newVals map[string]interface{}
//bson.Unmarshal(mapBytes, newVals)
//if reflect.DeepEqual(newVals, vals) {
// fmt.Printf("OK")
// }
}
func stepIn(bs map[string]interface{}) error {
finished := true
for key, val := range bs {
switch v := val.(type) {
case map[string]interface{}:
fmt.Printf("m[s]i\n")
err := stepIn(v)
if err != nil {
return err
}
case map[interface{}]interface{}:
fmt.Printf("m[i]i\n")
newMap := make(map[string]interface{})
for k, valVal := range val.(map[interface{}]interface{}) {
switch ktype := k.(type) {
case string:
fmt.Printf("inner ktype string: %v\n", ktype)
newMap[ktype] = valVal
default:
fmt.Printf("not ktype string: %v", ktype)
return errors.New("bad map key")
}
}
err := stepIn(newMap)
if err != nil {
return err
}
bs[key] = newMap
finished = false
case []interface{}:
fmt.Printf("[]i\n")
// for j, lval := range val {
// return stepInList(lval)
// }
//finished = false
return errors.New("oops")
default:
//bson can handle this
//return bson.Marshal(map[string]interface{}{key: val})
}
}
if finished {
return nil
}
return stepIn(bs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment