readme.md
1# orderedmap
2
3A golang data type equivalent to python's collections.OrderedDict
4
5Retains order of keys in maps
6
7Can be JSON serialized / deserialized
8
9# Usage
10
11```go
12package main
13
14import (
15 "encoding/json"
16 "github.com/iancoleman/orderedmap"
17)
18
19func main() {
20
21 // use New() instead of o := map[string]interface{}{}
22 o := orderedmap.New()
23
24 // use SetEscapeHTML() to whether escape problematic HTML characters or not, defaults is true
25 o.SetEscapeHTML(false)
26
27 // use Set instead of o["a"] = 1
28 o.Set("a", 1)
29
30 // add some value with special characters
31 o.Set("b", "\\.<>[]{}_-")
32
33 // use Get instead of i, ok := o["a"]
34 val, ok := o.Get("a")
35
36 // use Keys instead of for k, v := range o
37 keys := o.Keys()
38 for _, k := range keys {
39 v, _ := o.Get(k)
40 }
41
42 // use o.Delete instead of delete(o, key)
43 o.Delete("a")
44
45 // serialize to a json string using encoding/json
46 bytes, err := json.Marshal(o)
47 prettyBytes, err := json.MarshalIndent(o, "", " ")
48
49 // deserialize a json string using encoding/json
50 // all maps (including nested maps) will be parsed as orderedmaps
51 s := `{"a": 1}`
52 err := json.Unmarshal([]byte(s), &o)
53
54 // sort the keys
55 o.SortKeys(sort.Strings)
56
57 // sort by Pair
58 o.Sort(func(a *orderedmap.Pair, b *orderedmap.Pair) bool {
59 return a.Value().(float64) < b.Value().(float64)
60 })
61}
62```
63
64# Caveats
65
66* OrderedMap only takes strings for the key, as per [the JSON spec](http://json.org/).
67
68# Tests
69
70```
71go test
72```
73
74# Alternatives
75
76None of the alternatives offer JSON serialization.
77
78* [cevaris/ordered_map](https://github.com/cevaris/ordered_map)
79* [mantyr/iterator](https://github.com/mantyr/iterator)
80