Skip to content

Instantly share code, notes, and snippets.

@kevin-cantwell
Created April 8, 2014 19:14
Show Gist options
  • Save kevin-cantwell/10173951 to your computer and use it in GitHub Desktop.
Save kevin-cantwell/10173951 to your computer and use it in GitHub Desktop.
package myjson
import (
"fmt"
"strings"
)
type JsonData map[string]interface{}
func (d JsonData) Int64(dotPath string) (int64, error) {
value := d.Value(dotPath)
if val, ok := value.(float64); ok {
return int64(val), nil
} else {
return 0, fmt.Errorf("parse error: expected %v at %v to be float64, but was %T", value, dotPath, value)
}
}
func (d JsonData) String(dotPath string) (string, error) {
value := d.Value(dotPath)
if val, ok := value.(string); ok {
return val, nil
} else {
return "", fmt.Errorf("parse error: expected %v at %v to be string, but was %T", value, dotPath, value)
}
}
func (d JsonData) Value(dotPath string) interface{} {
keys := strings.Split(dotPath, ".")
var current interface{}
current = d
for i := 0; i < len(keys); i++ {
switch current.(type) {
case JsonData:
current = (current.(JsonData))[keys[i]]
case map[string]interface{}:
current = (current.(map[string]interface{}))[keys[i]]
default:
return nil
}
}
return current
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment