diff --git a/gjson.go b/gjson.go index a27840f..0da3221 100644 --- a/gjson.go +++ b/gjson.go @@ -105,6 +105,16 @@ func (t Result) String() string { } } +// Bytes returns the value as a byte slice (no copy). +func (t Result) Bytes() []byte { + switch t.Type { + default: + return stringBytes(t.Raw) + case String: + return stringBytes(t.Str) + } +} + // Bool returns an boolean representation. func (t Result) Bool() bool { switch t.Type { @@ -515,9 +525,9 @@ func Parse(json string) Result { } // ParseBytes parses the json and returns a result. -// If working with bytes, this method preferred over Parse(string(data)) +// If working with bytes, this method is preferred over Parse(string(data)) func ParseBytes(json []byte) Result { - return Parse(string(json)) + return Parse(bytesString(json)) } func squash(json string) string { diff --git a/gjson_test.go b/gjson_test.go index 079e1cf..574154a 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -367,6 +367,13 @@ func TestTypes(t *testing.T) { assert(t, (Result{Type: True}).Type.String() == "True") assert(t, (Result{Type: JSON}).Type.String() == "JSON") assert(t, (Result{Type: 100}).Type.String() == "") + + // bytes + assert(t, string((Result{Type: True, Raw: "true"}).Bytes()) == "true") + assert(t, string((Result{Type: String, Str: "value"}).Bytes()) == "value") + assert(t, string((Result{Type: Number, Raw: "1"}).Bytes()) == "1") + assert(t, (Result{Type: 100}).Bytes() == nil) + // bool assert(t, (Result{Type: True}).Bool() == true) assert(t, (Result{Type: False}).Bool() == false) @@ -393,11 +400,13 @@ func TestTypes(t *testing.T) { assert(t, (Result{Type: True}).Int() == 1) assert(t, (Result{Type: False}).Int() == 0) assert(t, (Result{Type: Number, Num: 1}).Int() == 1) + // uint assert(t, (Result{Type: String, Str: "1"}).Uint() == 1) assert(t, (Result{Type: True}).Uint() == 1) assert(t, (Result{Type: False}).Uint() == 0) assert(t, (Result{Type: Number, Num: 1}).Uint() == 1) + // float assert(t, (Result{Type: String, Str: "1"}).Float() == 1) assert(t, (Result{Type: True}).Float() == 1)