Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg committed Sep 24, 2023
1 parent 2de94be commit 96e85b1
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
6 changes: 4 additions & 2 deletions jsn.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@ func (n N) MarshalJSON() ([]byte, error) {
return []byte(n), nil
}

// Unmarshal ...
// Unmarshal only 1 JSON entity from the input.
// Disallows unknown fields if the argument is a struct.
func Unmarshal(b []byte, v any) error {
return UnmarshalFrom(bytes.NewReader(b), v)
}

// UnmarshalFrom ...
// UnmarshalFrom only 1 JSON entity from the input.
// Disallows unknown fields if the argument is a struct.
func UnmarshalFrom(r io.Reader, v any) error {
d := json.NewDecoder(r)
d.DisallowUnknownFields()
Expand Down
61 changes: 61 additions & 0 deletions jsn_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package jsn

import (
"reflect"
"testing"
)

func TestUnmarshal(t *testing.T) {
testCases := []struct {
input string
want any
errStr string
}{
{
input: `"abc"`,
want: "abc",
},
{
input: `123`,
want: float64(123),
},
{
input: `{"abc": 123}`,
want: map[string]any{"abc": float64(123)},
},
{
input: `{"abc": 123} `,
want: map[string]any{"abc": float64(123)},
},
{
input: ` ["abc", 123] `,
want: []any{"abc", float64(123)},
},
{
input: `{"abc": 123}a`,
errStr: "body must contain only one JSON object",
},
{
input: `{"abc`,
errStr: "unexpected EOF",
},
}

for _, tc := range testCases {
var val any
err := Unmarshal([]byte(tc.input), &val)
if err != nil {
if tc.errStr == "" {
t.Fatal(err)
}
if have := err.Error(); have != tc.errStr {
t.Fatalf("\nhave: %+v\nwant: %+v\n", have, tc.errStr)
}
continue
}

if !reflect.DeepEqual(val, tc.want) {
t.Fatalf("\nhave: %+v\nwant: %+v\n", val, tc.want)
}
}
}

0 comments on commit 96e85b1

Please sign in to comment.