From 60912bdf656c3128f0b3a4c8124880e933f1d005 Mon Sep 17 00:00:00 2001 From: vishalnayak Date: Thu, 7 Jul 2016 10:51:49 -0400 Subject: [PATCH] Added jsonutil helper --- helper/jsonutil/json.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 helper/jsonutil/json.go diff --git a/helper/jsonutil/json.go b/helper/jsonutil/json.go new file mode 100644 index 000000000..27256b8db --- /dev/null +++ b/helper/jsonutil/json.go @@ -0,0 +1,38 @@ +package jsonutil + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "reflect" +) + +func EncodeJSON(in interface{}) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + if err := enc.Encode(in); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func DecodeJSON(data []byte, out interface{}) error { + // Decoding requires a pointer type to be supplied + value := reflect.ValueOf(out) + if value.Kind() != reflect.Ptr { + return fmt.Errorf("decoding the value into an invalid type: %v", reflect.TypeOf(out)) + } + + return DecodeJSONFromReader(bytes.NewReader(data), out) +} + +func DecodeJSONFromReader(r io.Reader, out interface{}) error { + dec := json.NewDecoder(r) + + // While decoding JSON values, intepret the integer values as numbers instead of floats. + dec.UseNumber() + + // Since 'out' is an interface representing a pointer, pass it to the decoder without an '&' + return dec.Decode(out) +}