Skip to content

Commit

Permalink
Add unmarshal funcs
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg committed Sep 23, 2023
1 parent d09f379 commit 7496f0b
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions jsn.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package jsn

import (
"bytes"
"encoding/json"
"errors"
"io"
)

// A represents JSON array.
type A = []any

Expand All @@ -15,3 +22,24 @@ type N string
func (n N) MarshalJSON() ([]byte, error) {
return []byte(n), nil
}

// Unmarshal ...
func Unmarshal(b []byte, v any) error {
return UnmarshalFrom(bytes.NewReader(b), v)
}

// UnmarshalFrom ...
func UnmarshalFrom(r io.Reader, v any) error {
d := json.NewDecoder(r)
d.DisallowUnknownFields()

if err := d.Decode(v); err != nil {
return err
}
if d.More() {
return errX
}
return nil
}

var errX = errors.New("body must contain only one JSON object")

0 comments on commit 7496f0b

Please sign in to comment.