Last active
December 22, 2021 14:37
-
-
Save Anil8753/aefc9949b42831fb2e10b69b47360785 to your computer and use it in GitHub Desktop.
json.Marshal() retains the struct keys order in which they are define in the struct. This snippet `JsonRemarshal` sort the struct keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // You can edit this code! | |
| // Click here and start typing. | |
| package main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| ) | |
| type AmountType struct { | |
| Value string `json:"value"` | |
| Name string `json:"name"` | |
| } | |
| type Data struct { | |
| Source string `json:"source"` | |
| Target string `json:"target"` | |
| Amount AmountType `json:"amount"` | |
| } | |
| func JsonRemarshal(bytes []byte) ([]byte, error) { | |
| var ifce interface{} | |
| err := json.Unmarshal(bytes, &ifce) | |
| if err != nil { | |
| return []byte{}, err | |
| } | |
| output, err := json.Marshal(ifce) | |
| if err != nil { | |
| return []byte{}, err | |
| } | |
| return output, nil | |
| } | |
| func main() { | |
| at := AmountType{Value: "100", Name: "$"} | |
| data := Data{Source: "Alice", Target: "Bob", Amount: at} | |
| dataBytes, err := json.Marshal(data) | |
| if err != nil { | |
| fmt.Println(err) | |
| } | |
| fmt.Println(string(dataBytes)) | |
| n, _ := JsonRemarshal(dataBytes) | |
| fmt.Println(string(n)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output