Skip to content

Instantly share code, notes, and snippets.

@Anil8753
Last active December 22, 2021 14:37
Show Gist options
  • Save Anil8753/aefc9949b42831fb2e10b69b47360785 to your computer and use it in GitHub Desktop.
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
// 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))
}
@Anil8753
Copy link
Author

Anil8753 commented Dec 22, 2021

Output

Original ->  {"source":"Alice","target":"Bob","amount":{"value":"100","name":"$"}}
Sorted Keys ->  {"amount":{"name":"$","value":"100"},"source":"Alice","target":"Bob"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment