📖 3 min read (~ 500 words).

Keep key order

The task: read a document whose schema you do not own, change nothing, and write it back with the keys where the author put them.

The file

// The keys are in no sorted order, and the order is the author's.
const src = `zebra: 1
apple:
  b: 2
  a: 1
mango: [x]
`

Full source: docs/examples/decoding/keyorder/example_test.go

The default sorts the keys

var v any
if err := codec.Unmarshal([]byte(src), &v); err != nil {
	fmt.Println(err)

	return
}
out, err := codec.Marshal(v)
if err != nil {
	fmt.Println(err)

	return
}
fmt.Printf("%T\n%s", v, out)

Full source: docs/examples/decoding/keyorder/example_test.go

map[string]interface {}
apple:
  a: 1
  b: 2
mango:
- x
zebra: 1

Full source: docs/examples/decoding/keyorder/example_test.go

Into any, a mapping decodes to a map[string]any. A Go map holds no order, and Marshal writes a map’s keys sorted, so zebra moves to the end and apple’s keys swap.

Decode with UseOrderedMap

var v any
if err := codec.Unmarshal([]byte(src), &v, codec.UseOrderedMap()); err != nil {
	fmt.Println(err)

	return
}
out, err := codec.Marshal(v)
if err != nil {
	fmt.Println(err)

	return
}
fmt.Printf("%T\n%s", v, out)

Full source: docs/examples/decoding/keyorder/example_test.go

codec.MapSlice
zebra: 1
apple:
  b: 2
  a: 1
mango:
- x

Full source: docs/examples/decoding/keyorder/example_test.go

codec.UseOrderedMap decodes every mapping whose destination names no type into a codec.MapSlice, at every depth, and Marshal writes a MapSlice in its own order.

Read a MapSlice

m := v.(codec.MapSlice)
for key, value := range m.All() {
	fmt.Printf("%v: %T\n", key, value)
}

apple, _ := m.Get("apple")
for key := range apple.(codec.MapSlice).Keys() {
	fmt.Println("apple.", key)
}

Full source: docs/examples/decoding/keyorder/example_test.go

zebra: uint64
apple: codec.MapSlice
mango: []interface {}
apple. b
apple. a

Full source: docs/examples/decoding/keyorder/example_test.go

All yields each key and value in order, Keys and Values one side each, and Get looks a key up. A key keeps the type it resolves to, as in a map[any]any: 1: gives uint64(1), not "1". codec.UseStringKeys reads every key as text instead.

A field typed MapSlice

// Env keeps its order whatever the options: the field names MapSlice.
type Service struct {
	Env codec.MapSlice `yaml:"env"`
}

	var s Service
	if err := codec.Unmarshal([]byte("env:\n  PATH: /bin\n  HOME: /root\n"), &s); err != nil {
		fmt.Println(err)

		return
	}
	j, err := s.Env.MarshalJSON()
	fmt.Println(string(j), err)

Full source: docs/examples/decoding/keyorder/example_test.go

var s Service
if err := codec.Unmarshal([]byte("env:\n  PATH: /bin\n  HOME: /root\n"), &s); err != nil {
	fmt.Println(err)

	return
}
j, err := s.Env.MarshalJSON()
fmt.Println(string(j), err)

Full source: docs/examples/decoding/keyorder/example_test.go

{"PATH":"/bin","HOME":"/root"} <nil>

Full source: docs/examples/decoding/keyorder/example_test.go

A field typed codec.MapSlice keeps its order with no option, and its MarshalJSON writes the members in that order.

Variations

  • !!omap. codec.MapSliceSeq reads and writes the tagged form, a sequence of one-entry mappings. A decode into any builds one for a node tagged !!omap.
  • The comments too. A MapSlice keeps keys and values only. To keep the comments and the layout as well, edit the document: see Change one value, keep the file.

Reference: Marshal and Unmarshal.