Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
9 changes: 9 additions & 0 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down