forked from cevaris/ordered_map
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_codec.go
45 lines (40 loc) · 899 Bytes
/
json_codec.go
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
package orderedmap
import (
"errors"
"fmt"
"strings"
"encoding/json"
"gopkg.in/yaml.v2"
)
func (om OrderedMap) MarshalJSON() ([]byte, error) {
// as JSON specifies key must be string, check if the keys can be casted to string first
iter := om.IterFunc()
for kv, ok := iter(); ok; kv, ok = iter() {
_, ok := kv.Key.(string)
if ok != true {
return nil, errors.New(fmt.Sprintf("key: %v is not string", kv.Key))
}
}
s := "{"
isNext := false
iter = om.IterFunc()
for kv, ok := iter(); ok; kv, ok = iter() {
if isNext {
s += ","
}
k := kv.Key.(string)
s += fmt.Sprintf("\"%s\":", strings.Replace(k, `"`, `\"`, -1))
v := kv.Value
vBytes, err := json.Marshal(v)
if err != nil {
return nil, err
}
s += string(vBytes)
isNext = true
}
s += "}"
return []byte(s), nil
}
func (om *OrderedMap) UnmarshalJSON(b []byte) error {
return yaml.Unmarshal(b, om)
}