Created
December 10, 2012 02:01
-
-
Save mbeale/4247971 to your computer and use it in GitHub Desktop.
Dynamic JSON sample golang #4
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
type JSONContainer struct { | |
data []interface{} | |
} | |
func (j *JSONContainer) All() (objects []JSONObject) { | |
for _, v := range j.data { | |
objects = append(objects, JSONObject{data: v}) | |
} | |
return | |
} | |
func (j *JSONContainer) GetByKey(val int) (json JSONObject, e error) { | |
return | |
} | |
type JSONObject struct { | |
data interface{} | |
} | |
func (j *JSONObject) Get(value string) (string,error) { | |
//get the root map | |
m := j.createMap(); | |
//get all the segments | |
segments := strings.Split(value,".") | |
for i,v := range segments { | |
if val, success := m[v]; success { | |
//if this is the ultimate segment | |
if i + 1 == len(explode) { | |
if s, isstring := val.(string); isstring { | |
return s, nil | |
} else { | |
return "", errors.New("Value is not a string"); | |
} | |
} else { | |
//type cast the interface into a map | |
m, success = m[v].(map[string]interface{}) | |
if !success { | |
return "", errors.New("Can not convert value to map") | |
} | |
} | |
} | |
} | |
return "", errors.New("Key does not exist") | |
} | |
func (j *JSONObject) createMap() (map[string]interface{}) { | |
return j.data.(map[string]interface{}) | |
} | |
func MakeJSONContainer(rawData []byte) (j JSONContainer, e error){ | |
if err := json.Unmarshal(rawData, &j.data); err != nil { | |
return j, err | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment