I have a map
{
"m_key": 123,
"z_key": 123,
"a_key": 123,
"f_key": 123
}
When i'm trying to make a json from it and print it my json becomes sorted by key and i get json:
{
"a_key": 123,
"f_key": 123,
"m_key": 123,
"z_key": 123
}
To answer the original question use an ordered map
package main
import (
"encoding/json"
"fmt"
"github.com/iancoleman/orderedmap"
)
func main() {
o := orderedmap.New()
// use Set instead of o["a"] = 1
o.Set("m_key", "123") // go json.Marshall doesn't like integers
o.Set("z_key", "123")
o.Set("a_key", "123")
o.Set("f_key", "123")
// serialize to a json string using encoding/json
prettyBytes, _ := json.Marshal(o)
fmt.Printf("%s", prettyBytes)
}
But according the spec https://json-schema.org/latest/json-schema-core.html#rfc.section.4.2 there is no guarantee that the ordering of maps is honoured, so it's probably better to use an array instead for json output
// convert to array
fmt.Printf("
")
arr := make([]string, 8)
c := 0
for _, k := range o.Keys() {
arr[c] = k
c++
v, _ := o.Get(k)
arr[c], _ = v.(string)
c++
}
morePretty, _ := json.Marshal(arr)
fmt.Printf("%s", morePretty)
When the array is reloaded it will be in the correct order