Skip to content

Add an interface to support any decoder #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
28 changes: 19 additions & 9 deletions node.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"sort"
"strings"
)

// An interface to provide custom json decoder
type DecoderInterface interface {
Decode(v interface{}) error
}

// A NodeType is the type of a Node.
type NodeType uint

Expand Down Expand Up @@ -189,21 +193,27 @@ func parseValue(x interface{}, top *Node, level int) {
}
}

func parse(b []byte) (*Node, error) {
func parse(decoder DecoderInterface) (*Node, error) {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
if err := decoder.Decode(&v); err != nil {
return nil, err
}
doc := &Node{Type: DocumentNode}
parseValue(v, doc, 1)
return doc, nil
}

// Parse JSON document.
// Parse JSON document from Reader
func Parse(r io.Reader) (*Node, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return parse(b)
return parse(json.NewDecoder(r))
}

// Parse JSON document from bytes
func ParseFromBytes(b []byte) (*Node, error) {
return parse(json.NewDecoder(strings.NewReader(string(b))))
}

// Parse JSON with custom decoder
func ParseWithDecoder(decoder DecoderInterface) (*Node, error) {
return parse(decoder)
}