From c4e6e61fb651eb45fed0c1a90e036cedd3205786 Mon Sep 17 00:00:00 2001 From: Mike Bazuin Date: Mon, 21 Jan 2019 11:18:53 +0100 Subject: [PATCH] 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 --- objects/builtin_json.go | 18 ++++++++++++++++++ objects/builtins.go | 4 ++++ runtime/vm_builtin_test.go | 15 +++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 objects/builtin_json.go diff --git a/objects/builtin_json.go b/objects/builtin_json.go new file mode 100644 index 0000000..38e76cd --- /dev/null +++ b/objects/builtin_json.go @@ -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 +} diff --git a/objects/builtins.go b/objects/builtins.go index fe7085e..6e9f898 100644 --- a/objects/builtins.go +++ b/objects/builtins.go @@ -80,4 +80,8 @@ var Builtins = []NamedBuiltinFunc{ Name: "is_undefined", Func: builtinIsUndefined, }, + { + Name: "to_json", + Func: builtinToJSON, + }, } diff --git a/runtime/vm_builtin_test.go b/runtime/vm_builtin_test.go index 587269e..73d164a 100644 --- a/runtime/vm_builtin_test.go +++ b/runtime/vm_builtin_test.go @@ -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]]")) + }