Skip to content

Commit bb01833

Browse files
committed
support XPath query for JSON
1 parent dc62b9c commit bb01833

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

html.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,7 @@ func ParseMediaType(v string) MediaType {
4848
}
4949
}
5050

51-
// ParseHTML parses an HTTP response as HTML document.
52-
func ParseHTML(resp *http.Response) (*html.Node, error) {
51+
func readResponseBody(resp *http.Response) (io.Reader, error) {
5352
var (
5453
ce encoding.Encoding
5554
r io.Reader = resp.Body
@@ -83,5 +82,14 @@ func ParseHTML(resp *http.Response) (*html.Node, error) {
8382
if ce != encoding.Nop {
8483
r = transform.NewReader(r, ce.NewDecoder())
8584
}
85+
return r, nil
86+
}
87+
88+
// ParseHTML parses an HTTP response as HTML document.
89+
func ParseHTML(resp *http.Response) (*html.Node, error) {
90+
r, err := readResponseBody(resp)
91+
if err != nil {
92+
return nil, err
93+
}
8694
return htmlquery.Parse(r)
8795
}

json.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package antch
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/antchfx/jsonquery"
7+
)
8+
9+
// ParseJSON parses an HTTP response as JSON document.
10+
func ParseJSON(resp *http.Response) (*jsonquery.Node, error) {
11+
r, err := readResponseBody(resp)
12+
if err != nil {
13+
return nil, err
14+
}
15+
return jsonquery.Parse(r)
16+
}

json_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package antch
2+
3+
import (
4+
"io/ioutil"
5+
"net/http"
6+
"strings"
7+
"testing"
8+
)
9+
10+
var testJSON = `{"name":"John","age":31,"city":"New York"}`
11+
12+
func TestParseJSON(t *testing.T) {
13+
res := &http.Response{
14+
Body: ioutil.NopCloser(strings.NewReader(testJSON)),
15+
}
16+
_, err := ParseJSON(res)
17+
if err != nil {
18+
t.Fatal(err)
19+
}
20+
}

0 commit comments

Comments
 (0)