-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathjson.go
61 lines (55 loc) · 1.21 KB
/
json.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
package js
import (
"encoding/json"
"errors"
"fmt"
"sync"
)
var (
_ json.Marshaler = Value{}
_ json.Unmarshaler = (*Value)(nil)
)
var (
jsonObj Ref
jsonParse Ref
jsonStringify Ref
jsonOnce sync.Once
)
func initJSON() {
jsonObj = global.Get("JSON")
if jsonObj == undefined {
return
}
jsonParse = jsonObj.Get("parse")
jsonStringify = jsonObj.Get("stringify")
}
// MarshalJSON encodes a value into JSON by using native JavaScript function (JSON.stringify).
func (v Value) MarshalJSON() ([]byte, error) {
jsonOnce.Do(initJSON)
if jsonStringify == undefined {
return nil, errors.New("json encoding is not supported")
}
if v.Ref == undefined {
return []byte("null"), nil
}
s := jsonStringify.Invoke(v.Ref).String()
return []byte(s), nil
}
// UnmarshalJSON decodes a value from JSON by using native JavaScript functions (JSON.parse).
func (v *Value) UnmarshalJSON(p []byte) (err error) {
jsonOnce.Do(initJSON)
if jsonParse == undefined {
return errors.New("json decoding is not supported")
}
defer func() {
if r := recover(); r != nil {
if e, ok := r.(error); ok {
err = e
} else {
err = fmt.Errorf("%v", r)
}
}
}()
v.Ref = jsonParse.Invoke(string(p))
return err
}