A Go map that preserves insertion order for manual operations and JSON marshalling. Nested JSON objects are unmarshalled as ordered maps too.
go get github.com/cornelk/orderedmapRequires Go 1.24 or later.
package main
import (
"encoding/json"
"fmt"
"github.com/cornelk/orderedmap"
)
func main() {
var m orderedmap.Map
m.Set("name", "Alice")
m.Set("age", 30)
if value, ok := m.Get("name"); ok {
fmt.Println(value)
}
m.Range(func(key string, value any) bool {
fmt.Printf("%s: %v\n", key, value)
return true
})
data, _ := json.Marshal(&m)
fmt.Println(string(data))
}JSON input order is preserved when unmarshalling and marshalling:
var m orderedmap.Map
input := `{"423":"abc","231":"dbh","152":"xyz"}`
json.Unmarshal([]byte(input), &m)
output, _ := json.Marshal(&m)
// Output: {"423":"abc","231":"dbh","152":"xyz"}Set(key string, value any)adds or updates a value without moving existing keys.Get(key string) (any, bool)retrieves a value.Delete(key string) boolremoves a value.GetAndDelete(key string) (any, bool)retrieves and removes a value.Clear()removes all values.Len() intreturns the number of entries.Range(func(key string, value any) bool)iterates in insertion order.
Apache-2.0 License - See LICENSE file for details.