This commit is contained in:
Alex Dadgar
2016-08-08 16:16:12 -07:00
parent 6a400698ae
commit d5380974a0
2 changed files with 54 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
package jsonutil
import (
"bytes"
"encoding/json"
"fmt"
"io"
)
// Encodes/Marshals the given object into JSON
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
}
// Decodes/Unmarshals the given JSON into a desired object
func DecodeJSON(data []byte, out interface{}) error {
if data == nil {
return fmt.Errorf("'data' being decoded is nil")
}
if out == nil {
return fmt.Errorf("output parameter 'out' is nil")
}
return DecodeJSONFromReader(bytes.NewReader(data), out)
}
// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object
func DecodeJSONFromReader(r io.Reader, out interface{}) error {
if r == nil {
return fmt.Errorf("'io.Reader' being decoded is nil")
}
if out == nil {
return fmt.Errorf("output parameter 'out' is nil")
}
dec := json.NewDecoder(r)
// While decoding JSON values, intepret the integer values as `json.Number`s instead of `float64`.
dec.UseNumber()
// Since 'out' is an interface representing a pointer, pass it to the decoder without an '&'
return dec.Decode(out)
}

6
vendor/vendor.json vendored
View File

@@ -628,6 +628,12 @@
"revision": "bcf98fa8d61d1870c3af689f1b090b29a9c12d8c",
"revisionTime": "2016-08-02T20:35:37Z"
},
{
"checksumSHA1": "5lR6EdY0ARRdKAq3hZcL38STD8Q=",
"path": "github.com/hashicorp/vault/helper/jsonutil",
"revision": "bcf98fa8d61d1870c3af689f1b090b29a9c12d8c",
"revisionTime": "2016-08-02T20:35:37Z"
},
{
"checksumSHA1": "VMaF3Q7RIrRzvbnPbqxuSLryOvc=",
"path": "github.com/hashicorp/yamux",