Added builtin function from_json
objects/builtin_json.go: - Added function builtinFromJSON objects/builtins.go: - Added builtin function from_json runtim/vm_builtin_test.go: - Added tests for builtin function from_json
This commit is contained in:
parent
c4e6e61fb6
commit
e94b3dab0f
3 changed files with 46 additions and 0 deletions
|
@ -16,3 +16,33 @@ func builtinToJSON(args ...Object) (Object, error) {
|
|||
|
||||
return &Bytes{Value: res}, nil
|
||||
}
|
||||
|
||||
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 nil, err
|
||||
}
|
||||
case *String:
|
||||
err := json.Unmarshal([]byte(o.Value), &target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return nil, ErrInvalidTypeConversion
|
||||
}
|
||||
|
||||
res, err := FromInterface(target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
|
|
@ -84,4 +84,8 @@ var Builtins = []NamedBuiltinFunc{
|
|||
Name: "to_json",
|
||||
Func: builtinToJSON,
|
||||
},
|
||||
{
|
||||
Name: "from_json",
|
||||
Func: builtinFromJSON,
|
||||
},
|
||||
}
|
||||
|
|
|
@ -128,4 +128,16 @@ func TestBuiltinFunction(t *testing.T) {
|
|||
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]]"))
|
||||
|
||||
// from_json
|
||||
expect(t, `out = from_json("{\"foo\":5}").foo`, 5.0)
|
||||
expect(t, `out = from_json("{\"foo\":\"bar\"}").foo`, "bar")
|
||||
expect(t, `out = from_json("{\"foo\":1.8}").foo`, 1.8)
|
||||
expect(t, `out = from_json("{\"foo\":true}").foo`, true)
|
||||
expect(t, `out = from_json("{\"foo\":[\"bar\",1,1.8,56,true]}").foo`, ARR{"bar", 1.0, 1.8, 56.0, true})
|
||||
expect(t, `out = from_json("{\"foo\":[[\"bar\",1],[\"bar\",1]]}").foo[0]`, ARR{"bar", 1.0})
|
||||
expect(t, `out = from_json("{\"foo\":{\"bool\":true,\"char\":56,\"float\":1.8,\"int\":1,\"string\":\"bar\"}}").foo.bool`, true)
|
||||
expect(t, `out = from_json("{\"foo\":{\"map1\":{\"string\":\"bar\"},\"map2\":{\"int\":\"1\"}}}").foo.map1.string`, "bar")
|
||||
|
||||
expect(t, `out = from_json("5")`, 5.0)
|
||||
expect(t, `out = from_json("[\"bar\",1,1.8,56,true]")`, ARR{"bar", 1.0, 1.8, 56.0, true})
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue