Skip to content

Instantly share code, notes, and snippets.

@mbeale
Created December 8, 2012 23:38
Show Gist options
  • Save mbeale/4242532 to your computer and use it in GitHub Desktop.
Save mbeale/4242532 to your computer and use it in GitHub Desktop.
Dynamic JSON sample golang #2
//Document Container
type JSONContainer struct {
data []interface{}
}
//Return all objects
func (j *JSONContainer) All() (objects []JSONObject) {
for _, v := range j.data {
newJSONObject := JSONObject{data: v}
objects = append(objects, newJSONObject)
}
return
}
//JSON Object container
type JSONObject struct {
data interface{}
}
//Search for a attribute
func (j *JSONObject) Get(val string) (string,error) {
m := j.createMap();
if val, success := m[val]; success {
return fmt.Sprintf("%s",val), nil
}
return "", errors.New("Key does not exist")
}
//Type casts the integer as a map
func (j *JSONObject) createMap() (map[string]interface{}) {
return j.data.(map[string]interface{})
}
//Function to create and intialize a container with a document
func DynamicJSON(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