Created
December 8, 2012 23:38
-
-
Save mbeale/4242532 to your computer and use it in GitHub Desktop.
Dynamic JSON sample golang #2
This file contains hidden or 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
//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