Skip to content

Commit

Permalink
Add unmarshal funcs (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored Sep 24, 2023
1 parent 1ef60ba commit d8927ad
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
30 changes: 30 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,26 @@ type N string
func (n N) MarshalJSON() ([]byte, error) {
return []byte(n), nil
}

// 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 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()

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

var errMore = errors.New("body must contain only one JSON entity")
65 changes: 65 additions & 0 deletions jsn_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
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 entity",
},
{
input: `[123]{"a":"b"}`,
errStr: "body must contain only one JSON entity",
},
{
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 d8927ad

Please sign in to comment.