summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/d5/tengo/objects/builtin_json.go
blob: c0810f7db16ad628c8e86220fe2b363daee1973f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package objects

import (
	"encoding/json"
)

// to_json(v object) => bytes
func builtinToJSON(args ...Object) (Object, error) {
	if len(args) != 1 {
		return nil, ErrWrongNumArguments
	}

	res, err := json.Marshal(objectToInterface(args[0]))
	if err != nil {
		return &Error{Value: &String{Value: err.Error()}}, nil
	}

	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
}