-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
48 lines (39 loc) · 1.2 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
//go:build js
package goji
import (
"encoding/json"
"syscall/js"
)
func init() {
JSON = jsonJS(js.Global().Get("JSON"))
}
// JSON is a wrapper for the JSON global object.
//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
var JSON jsonJS
type jsonJS js.Value
// Parse is a wrapper for the JSON parse static method.
//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
func (j jsonJS) Parse(text string) js.Value {
return js.Value(j).Call("parse", text)
}
// Stringify is a wrapper for the JSON stringify static method.
//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
func (j jsonJS) Stringify(value js.Value) string {
return js.Value(j).Call("stringify", value).String()
}
// MarshalJS marshals the given value into a js.Value.
func MarshalJS(v any) (js.Value, error) {
data, err := json.Marshal(v)
if err != nil {
return js.Undefined(), err
}
return JSON.Parse(string(data)), nil
}
// UnmarshalJS unmarshals the given js.Value into the given pointer.
func UnmarshalJS(value js.Value, v any) error {
text := JSON.Stringify(value)
return json.Unmarshal([]byte(text), v)
}