Add support for io.Reader as input #78

This commit is contained in:
u5surf 2018-08-02 00:10:10 +09:00
parent f92dbfc6b2
commit 0a2d1d5cf5
2 changed files with 33 additions and 0 deletions

View File

@ -2,9 +2,11 @@
package gjson
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"reflect"
"strconv"
"strings"
@ -1405,6 +1407,15 @@ func Get(json, path string) Result {
return c.value
}
// GetReader searches json for the specified path.
// If working with io.Reader, this method preferred over Get(string(data), path)
func GetReader(json io.Reader, path string) Result {
buf := new(bytes.Buffer)
buf.ReadFrom(json)
return Get(buf.String(), path)
}
// GetBytes searches json for the specified path.
// If working with bytes, this method preferred over Get(string(data), path)
func GetBytes(json []byte, path string) Result {

View File

@ -37,6 +37,28 @@ func TestRandomData(t *testing.T) {
}
}
func TestRandomValidReader(t *testing.T) {
var lstr string
defer func() {
if v := recover(); v != nil {
println("'" + hex.EncodeToString([]byte(lstr)) + "'")
println("'" + lstr + "'")
panic(v)
}
}()
rand.Seed(time.Now().UnixNano())
b := make([]byte, 200)
for i := 0; i < 2000000; i++ {
n, err := rand.Read(b[:rand.Int()%len(b)])
if err != nil {
t.Fatal(err)
}
lstr = string(b[:n])
GetReader(bytes.NewReader([]byte(lstr)), "reader")
Parse(lstr)
}
}
func TestRandomValidStrings(t *testing.T) {
rand.Seed(time.Now().UnixNano())
b := make([]byte, 200)