json - How do you Unmarshall into the correct order in Go? -


it seems if have interface{} in go in particular order , marshal []byte , unmarshal interface{}, should retain original order. not. result deepequal fails match 2 can see in program below.

package main  import (     "encoding/json"     "fmt"     "reflect" )  func main() {     var jd interface{}      j := map[string]interface{}{         "a": map[string]interface{}{"a": 1, "b": 2, "c": 3},         "b": map[string]interface{}{"a": 1, "b": 2, "c": 3},         "c": map[string]interface{}{             "a": map[string]interface{}{"a": 1, "b": 2, "c": 3},             "b": map[string]interface{}{"a": 1, "b": 2, "c": 3},             "c": map[string]interface{}{"a": 1, "b": 2, "c": 3},         },     }      s, _ := json.marshal(j)     _ = json.unmarshal(s, &jd)      fmt.println(string(s))     fmt.println(j)     fmt.println(jd)     if !reflect.deepequal(j, jd) {         fmt.println("fail!")     } } 

the results program random, typical result:

{"a":{"a":1,"b":2,"c":3},"b":{"a":1,"b":2,"c":3},"c":{"a":{"a":1,"b":2,"c":3},"b":{"a":1,"b":2,"c":3},"c":{"a":1,"b":2,"c":3}}}  map[b:map[a:1 b:2 c:3] c:map[c:map[a:1 b:2 c:3] a:map[b:2 c:3 a:1] b:map[a:1 b:2 c:3]] a:map[c:3 a:1 b:2]]  map[a:map[a:1 b:2 c:3] b:map[a:1 b:2 c:3] c:map[b:map[c:3 a:1 b:2] c:map[a:1 b:2 c:3] a:map[a:1 b:2 c:3]]]  fail! 

as can see, values marshal original order, unmarshal random order (multiple runs of program produce different results). result deepequal comparison fails every time (so far).

is bug in go? have workaround can suggest?

the go programming language specification

for statements

the iteration order on maps not specified , not guaranteed same 1 iteration next.

by design, iteration order on maps pseudorandom.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -