Added builtin function to_json
objects/builtin_json.go: - Added function builtinToJSON objects/builtins.go: - Added builtin function to_json runtime/vm_builtin_test.go - Added tests for builtin function to_json
This commit is contained in:
parent
65f84ec2d1
commit
c4e6e61fb6
3 changed files with 37 additions and 0 deletions
18
objects/builtin_json.go
Normal file
18
objects/builtin_json.go
Normal file
|
@ -0,0 +1,18 @@
|
|||
package objects
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
func builtinToJSON(args ...Object) (Object, error) {
|
||||
if len(args) != 1 {
|
||||
return nil, ErrWrongNumArguments
|
||||
}
|
||||
|
||||
res, err := json.Marshal(objectToInterface(args[0]))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Bytes{Value: res}, nil
|
||||
}
|
|
@ -80,4 +80,8 @@ var Builtins = []NamedBuiltinFunc{
|
|||
Name: "is_undefined",
|
||||
Func: builtinIsUndefined,
|
||||
},
|
||||
{
|
||||
Name: "to_json",
|
||||
Func: builtinToJSON,
|
||||
},
|
||||
}
|
||||
|
|
|
@ -113,4 +113,19 @@ func TestBuiltinFunction(t *testing.T) {
|
|||
|
||||
expect(t, `out = is_undefined(undefined)`, true)
|
||||
expect(t, `out = is_undefined(error(1))`, false)
|
||||
|
||||
// to_json
|
||||
expect(t, `out = to_json(5)`, []byte("5"))
|
||||
expect(t, `out = to_json({foo: 5})`, []byte("{\"foo\":5}"))
|
||||
expect(t, `out = to_json({foo: "bar"})`, []byte("{\"foo\":\"bar\"}"))
|
||||
expect(t, `out = to_json({foo: 1.8})`, []byte("{\"foo\":1.8}"))
|
||||
expect(t, `out = to_json({foo: true})`, []byte("{\"foo\":true}"))
|
||||
expect(t, `out = to_json({foo: '8'})`, []byte("{\"foo\":56}"))
|
||||
expect(t, `out = to_json({foo: bytes("foo")})`, []byte("{\"foo\":\"Zm9v\"}")) // json encoding returns []byte as base64 encoded string
|
||||
expect(t, `out = to_json({foo: ["bar", 1, 1.8, '8', true]})`, []byte("{\"foo\":[\"bar\",1,1.8,56,true]}"))
|
||||
expect(t, `out = to_json({foo: [["bar", 1], ["bar", 1]]})`, []byte("{\"foo\":[[\"bar\",1],[\"bar\",1]]}"))
|
||||
expect(t, `out = to_json({foo: {string: "bar", int: 1, float: 1.8, char: '8', bool: true}})`, []byte("{\"foo\":{\"bool\":true,\"char\":56,\"float\":1.8,\"int\":1,\"string\":\"bar\"}}"))
|
||||
expect(t, `out = to_json({foo: {map1: {string: "bar"}, map2: {int: "1"}}})`, []byte("{\"foo\":{\"map1\":{\"string\":\"bar\"},\"map2\":{\"int\":\"1\"}}}"))
|
||||
expect(t, `out = to_json([["bar", 1], ["bar", 1]])`, []byte("[[\"bar\",1],[\"bar\",1]]"))
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue