Skip to content

Instantly share code, notes, and snippets.

@straybro
Forked from mbeale/gist:4247971
Created May 12, 2020 21:52
Show Gist options
  • Save straybro/65e5d1755719787be96fe8e7a7d3b4c2 to your computer and use it in GitHub Desktop.
Save straybro/65e5d1755719787be96fe8e7a7d3b4c2 to your computer and use it in GitHub Desktop.
Dynamic JSON sample golang #4
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