Skip to content

Golang: map which keeps order even after JSON/YAML marshalling

License

Notifications You must be signed in to change notification settings

nicolasparada/go-ordered-map

Repository files navigation

Go Reference

Golang Ordered Map

Golang Ordered Map is a map data structure that maintains the order of the keys. It also supports JSON and YAML marshalling.

Installation

go get github.com/nicolasparada/go-ordered-map

Usage

package main

import (
	orderedmap "github.com/nicolasparada/go-ordered-map"
)

func main() {
	data := []byte(`{ "name": "John", "age": 30, "active": true }`)

	var unordered map[string]any{}
	if err := json.Unmarshal(data, &unordered); err != nil {
		panic(err)
	}

	var ordered orderedmap.OrderedMap[string, any]
	if err := json.Unmarshal(data, &ordered); err != nil {
		panic(err)
	}

	json.NewEncoder(os.Stdout).Encode(unordered) // will print in undefined order
	json.NewEncoder(os.Stdout).Encode(ordered) // will always print: {"name":"John","age":30,"active":true}
}