xgo/objects/builtin_json.go
2019-03-13 03:07:06 -07:00

65 lines
1.2 KiB
Go

package objects
import (
"encoding/json"
"github.com/d5/tengo"
)
// to_json(v object) => bytes
func builtinToJSON(args ...Object) (Object, error) {
if len(args) != 1 {
return nil, ErrWrongNumArguments
}
v := ToInterface(args[0])
if vErr, isErr := v.(error); isErr {
v = vErr.Error()
}
res, err := json.Marshal(v)
if err != nil {
return &Error{Value: &String{Value: err.Error()}}, nil
}
if len(res) > tengo.MaxBytesLen {
return nil, ErrBytesLimit
}
return &Bytes{Value: res}, nil
}
// from_json(data string/bytes) => object
func builtinFromJSON(args ...Object) (Object, error) {
if len(args) != 1 {
return nil, ErrWrongNumArguments
}
var target interface{}
switch o := args[0].(type) {
case *Bytes:
err := json.Unmarshal(o.Value, &target)
if err != nil {
return &Error{Value: &String{Value: err.Error()}}, nil
}
case *String:
err := json.Unmarshal([]byte(o.Value), &target)
if err != nil {
return &Error{Value: &String{Value: err.Error()}}, nil
}
default:
return nil, ErrInvalidArgumentType{
Name: "first",
Expected: "bytes/string",
Found: args[0].TypeName(),
}
}
res, err := FromInterface(target)
if err != nil {
return nil, err
}
return res, nil
}