From 0a2d1d5cf5760cc62a99b8a5f452854cbd234380 Mon Sep 17 00:00:00 2001 From: u5surf Date: Thu, 2 Aug 2018 00:10:10 +0900 Subject: [PATCH] Add support for io.Reader as input #78 --- gjson.go | 11 +++++++++++ gjson_test.go | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/gjson.go b/gjson.go index 1da1552..95acc54 100644 --- a/gjson.go +++ b/gjson.go @@ -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 { diff --git a/gjson_test.go b/gjson_test.go index 867fae6..1f639b6 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -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)