-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorderedjson.go
More file actions
86 lines (73 loc) · 1.4 KB
/
orderedjson.go
File metadata and controls
86 lines (73 loc) · 1.4 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package orderedjson
import (
"encoding/json"
"slices"
"strings"
)
type OrderedJSON struct {
keys []string
values map[string]any
}
func New() *OrderedJSON {
return &OrderedJSON{
keys: make([]string, 0),
values: make(map[string]any),
}
}
func (ojson *OrderedJSON) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(strings.NewReader(string(data)))
for dec.More() {
t, err := dec.Token()
if err != nil {
return err
}
var name string
var ok bool
if name, ok = t.(string); !ok {
continue
}
t, err = dec.Token()
if err != nil {
return err
}
ojson.keys = append(ojson.keys, name)
ojson.values[name] = t
}
return nil
}
func (oj *OrderedJSON) MarshalJSON() ([]byte, error) {
if len(oj.keys) == 0 {
return []byte("{}"), nil
}
var buf strings.Builder
buf.WriteString("{")
for i, key := range oj.keys {
if i > 0 {
buf.WriteString(",")
}
keyBytes, err := json.Marshal(key)
if err != nil {
return nil, err
}
buf.Write(keyBytes)
buf.WriteString(":")
valueBytes, err := json.Marshal(oj.values[key])
if err != nil {
return nil, err
}
buf.Write(valueBytes)
}
buf.WriteString("}")
return []byte(buf.String()), nil
}
func (oj *OrderedJSON) Delete(key string) {
if _, exists := oj.values[key]; exists {
delete(oj.values, key)
for i, k := range oj.keys {
if k == key {
oj.keys = slices.Delete(oj.keys, i, i+1)
break
}
}
}
}