Skip to content

Commit 288d600

Browse files
committed
Added ParsePrimitiveValue convenience function for users
1 parent 24fd329 commit 288d600

File tree

2 files changed

+108
-79
lines changed

2 files changed

+108
-79
lines changed

parser.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,3 +460,32 @@ func GetBoolean(data []byte, keys ...string) (val bool, err error) {
460460

461461
return
462462
}
463+
464+
// ParseBoolean parses a Boolean ValueType into a Go bool (not particularly useful, but here for completeness)
465+
func ParseBoolean(vbytes []byte) bool {
466+
return (vbytes[0] == 't') // assumes value is already validated by Get(), etc. as signaled by jtype == Boolean
467+
}
468+
469+
// ParseString parses a String ValueType into a Go []byte (the main parsing work is unescaping the JSON string)
470+
func ParseStringAsBytes(vbytes []byte) ([]byte, error) {
471+
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings (hopefully; the Go compiler might just always kick stackbuf[:] into the heap)
472+
return Unescape(vbytes, stackbuf[:])
473+
}
474+
475+
// ParseString parses a String ValueType into a Go string (the main parsing work is unescaping the JSON string)
476+
func ParseString(vbytes []byte) (string, error) {
477+
if vbytesUnesc, err := ParseStringAsBytes(vbytes); err != nil {
478+
return "", nil
479+
} else {
480+
return string(vbytesUnesc), nil
481+
}
482+
}
483+
484+
// ParseNumber parses a Number ValueType into a Go float64
485+
func ParseNumber(vbytes []byte) (float64, error) {
486+
if v, err := parseFloat(&vbytes); err != nil {
487+
return 0, MalformedValueError
488+
} else {
489+
return v, nil
490+
}
491+
}

0 commit comments

Comments
 (0)