Skip to content

Instantly share code, notes, and snippets.

@brunoksato
Created June 10, 2016 11:52
Show Gist options
  • Save brunoksato/03f4b57341d198a9293b287a3c204bb5 to your computer and use it in GitHub Desktop.
Save brunoksato/03f4b57341d198a9293b287a3c204bb5 to your computer and use it in GitHub Desktop.
helpers json
func ModelToJson(model interface{}) string {
j, err := json.Marshal(model)
if err != nil {
panic(fmt.Sprintf("Error %v encoding JSON for %v", err, model))
}
jsonStr := string(j)
v := reflect.Indirect(reflect.ValueOf(model))
ot := v.Type()
t := ot
isArray := false
if t.Kind() == reflect.Array || t.Kind() == reflect.Slice {
t = t.Elem()
isArray = true
} else if t.Kind() == reflect.Interface {
t = v.Elem().Type()
}
return jsonStr
}
func ModelToJsonMap(modl interface{}) map[string]interface{} {
jsonStr := ModelToJson(modl)
m := JsonToMap(jsonStr)
return m
}
func JsonToMap(jsonStr string) map[string]interface{} {
jsonMap := make(map[string]interface{})
err := json.Unmarshal([]byte(jsonStr), &jsonMap)
if err != nil {
panic(fmt.Sprintf("Error %v unmarshaling JSON for %v", err, jsonStr))
}
return jsonMap
}
func JsonToMapArray(jsonStr string) []map[string]interface{} {
var arr []map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &arr)
if err != nil {
panic(fmt.Sprintf("Error %v unmarshaling JSON for %v", err, jsonStr))
}
return arr
}
func JsonToModel(jsonStr string, item interface{}) error {
err := json.Unmarshal([]byte(jsonStr), &item)
if err == nil {
v := reflect.Indirect(reflect.ValueOf(item))
ot := v.Type()
t := ot
isArray := false
if t.Kind() == reflect.Array || t.Kind() == reflect.Slice {
t = t.Elem()
isArray = true
} else if t.Kind() == reflect.Interface {
t = v.Elem().Type()
}
}
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment