Skip to content

Instantly share code, notes, and snippets.

@VarunBatraIT
Forked from mbeale/gist:4247971
Created June 4, 2014 08:24
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 VarunBatraIT/8002fe7e5b3be9469aa2 to your computer and use it in GitHub Desktop.
Save VarunBatraIT/8002fe7e5b3be9469aa2 to your computer and use it in GitHub Desktop.
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