-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.go
More file actions
58 lines (53 loc) · 1.33 KB
/
json.go
File metadata and controls
58 lines (53 loc) · 1.33 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
package logger
import (
"bytes"
"encoding/json"
"fmt"
)
// KeyValuePair represents a key-value pair.
type KeyValuePair struct {
Key string
Value interface{}
}
// Marshal is a custom JSON marshalling function that preserves the order of keys.
func Marshal(pairs []KeyValuePair) ([]byte, error) {
// Estimate buffer size to reduce reallocations
buf := bytes.NewBuffer(make([]byte, 0, len(pairs)*32))
buf.WriteByte('{')
first := true
for _, pair := range pairs {
if !first {
buf.WriteByte(',')
}
first = false
buf.WriteString(`"` + pair.Key + `":`)
switch v := pair.Value.(type) {
case string:
buf.WriteString(`"` + v + `"`)
case int:
buf.WriteString(fmt.Sprintf("%d", v))
case float64:
buf.WriteString(fmt.Sprintf("%f", v))
default:
buf.WriteString(`null`)
}
}
buf.WriteByte('}')
return buf.Bytes(), nil
}
// Unmarshal is a custom JSON unmarshalling function.
func Unmarshal(data []byte, v interface{}) error {
err := json.Unmarshal(data, v)
if err != nil {
return fmt.Errorf("error unmarshalling JSON: %v", err)
}
return nil
}
// MapToKeyValuePairs converts a map to a slice of KeyValuePair
func MapToKeyValuePairs(m map[string]interface{}) []KeyValuePair {
pairs := make([]KeyValuePair, 0, len(m))
for k, v := range m {
pairs = append(pairs, KeyValuePair{Key: k, Value: v})
}
return pairs
}