aboutsummaryrefslogtreecommitdiff
path: root/model/objectNode.go
blob: cfa2a3074c2367e790bc9c11b8763b1efc45d966 (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
55
56
57
58
package model

import (
	"bytes"
	"fmt"
)

type ObjectNode struct {
	Value NodeObjectValue
}

func (n ObjectNode) Type() NodeType {
	return ObjectType
}

func (n *ObjectNode) MarshalJSON() ([]byte, error) {
	result := make([][]byte, 0, len(n.Value))
	for k, v := range n.Value {
		b, err := v.MarshalJSON()
		if err != nil {
			return nil, err
		}
		result = append(result, []byte(fmt.Sprintf("\"%s\": %s", k, b)))
	}
	return bytes.Join(
		[][]byte{
			[]byte("{"),
			bytes.Join(result, []byte(", ")),
			[]byte("}"),
		}, []byte("")), nil
}

func (n *ObjectNode) Get(k string) (Node, error) {
	child, ok := n.Value[k]
	if !ok {
		return nil, fmt.Errorf("field %s not found", k)
	}
	return child, nil
}

func (n *ObjectNode) Merge(n2 *ObjectNode) {
	for k, v := range n2.Value {
		n.Value[k] = v
	}
}

func (n *ObjectNode) Len() int {
	return len(n.Value)
}

func (n *ObjectNode) Set(v any) error {
	val, ok := v.(NodeObjectValue)
	if !ok {
		return fmt.Errorf("%v is not object", v)
	}
	n.Value = val
	return nil
}