-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
74 lines (67 loc) · 1.7 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package fetch
import (
"fmt"
"github.com/glossd/fetch/internal/json"
"reflect"
)
// Parse unmarshalls the JSON string into fetch.J without panicking.
// If unmarshalling encounters an error, Parse returns fetch.Nil type.
func Parse(s string) J {
j, err := Unmarshal[J](s)
if err != nil {
return jnil
}
return j
}
// UnmarshalJ sends J.String() to Unmarshal.
func UnmarshalJ[T any](j J) (T, error) {
if isJNil(j) {
var t T
return t, fmt.Errorf("cannot unmarshal nil J")
}
if IsJQError(j) {
var t T
return t, fmt.Errorf("cannot unmarshal JQerror")
}
return Unmarshal[T](j.String())
}
// Unmarshal is a generic wrapper for UnmarshalInto
func Unmarshal[T any](j string) (T, error) {
var t T
err := UnmarshalInto(j, &t)
return t, err
}
// UnmarshalInto calls the patched json.Unmarshal function.
// The only difference between them is it handles `fetch.J`
// and transforms `any` into fetch.J.
func UnmarshalInto(j string, v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return &json.InvalidUnmarshalError{reflect.TypeOf(v)}
}
rve := rv.Elem()
var isAny = rve.Kind() == reflect.Interface && rve.NumMethod() == 0
if isAny || rve.Type() == reflectTypeFor[J]() {
var a any
err := json.Unmarshal([]byte(j), &a)
if err != nil {
return err
}
switch u := a.(type) {
case bool:
rve.Set(reflect.ValueOf(B(u)))
case float64:
rve.Set(reflect.ValueOf(F(u)))
case string:
rve.Set(reflect.ValueOf(S(u)))
case map[string]any:
rve.Set(reflect.ValueOf(M(u)))
case []any:
rve.Set(reflect.ValueOf(A(u)))
default:
return fmt.Errorf("glossd/fetch: unmarshal unexpected type: %T", a)
}
return nil
}
return json.Unmarshal([]byte(j), v)
}