2019-01-21 13:18:53 +03:00
|
|
|
package objects
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2019-03-01 21:48:02 +03:00
|
|
|
|
|
|
|
"github.com/d5/tengo"
|
2019-01-21 13:18:53 +03:00
|
|
|
)
|
|
|
|
|
2019-02-21 03:26:11 +03:00
|
|
|
// to_json(v object) => bytes
|
2019-01-21 13:18:53 +03:00
|
|
|
func builtinToJSON(args ...Object) (Object, error) {
|
|
|
|
if len(args) != 1 {
|
|
|
|
return nil, ErrWrongNumArguments
|
|
|
|
}
|
|
|
|
|
2019-03-13 13:07:06 +03:00
|
|
|
v := ToInterface(args[0])
|
2019-03-13 12:25:21 +03:00
|
|
|
if vErr, isErr := v.(error); isErr {
|
|
|
|
v = vErr.Error()
|
|
|
|
}
|
|
|
|
|
|
|
|
res, err := json.Marshal(v)
|
2019-01-21 13:18:53 +03:00
|
|
|
if err != nil {
|
2019-02-21 03:26:11 +03:00
|
|
|
return &Error{Value: &String{Value: err.Error()}}, nil
|
2019-01-21 13:18:53 +03:00
|
|
|
}
|
|
|
|
|
2019-03-01 21:48:02 +03:00
|
|
|
if len(res) > tengo.MaxBytesLen {
|
|
|
|
return nil, ErrBytesLimit
|
|
|
|
}
|
|
|
|
|
2019-01-21 13:18:53 +03:00
|
|
|
return &Bytes{Value: res}, nil
|
|
|
|
}
|
2019-01-21 13:24:31 +03:00
|
|
|
|
2019-02-21 03:26:11 +03:00
|
|
|
// from_json(data string/bytes) => object
|
2019-01-21 13:24:31 +03:00
|
|
|
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 {
|
2019-02-21 03:26:11 +03:00
|
|
|
return &Error{Value: &String{Value: err.Error()}}, nil
|
2019-01-21 13:24:31 +03:00
|
|
|
}
|
|
|
|
case *String:
|
|
|
|
err := json.Unmarshal([]byte(o.Value), &target)
|
|
|
|
if err != nil {
|
2019-02-21 03:26:11 +03:00
|
|
|
return &Error{Value: &String{Value: err.Error()}}, nil
|
2019-01-21 13:24:31 +03:00
|
|
|
}
|
|
|
|
default:
|
2019-02-21 03:26:11 +03:00
|
|
|
return nil, ErrInvalidArgumentType{
|
|
|
|
Name: "first",
|
|
|
|
Expected: "bytes/string",
|
|
|
|
Found: args[0].TypeName(),
|
|
|
|
}
|
2019-01-21 13:24:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
res, err := FromInterface(target)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return res, nil
|
|
|
|
}
|