In python you can produce JSON with keys in sorted order by doing
import json print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4, separators=(',', ': '))
I have not found a similar option in Go. Any ideas how I can achieve similar behavior in go?
Enter your JSON into the first text area, or drag and drop a file, after, select the sort method you're going to use, key value requires the key name (if not specified selects the first key), click the example button to get an idea on how it works. The result will automatically sort and display in the output text area.
JSON return type is an array of objects. Hence sort method cannot be used directly to sort the array. However, we can use a comparer function as the argument of the 'sort' method to get the sorting implemented.
Golang provides multiple encoding and decoding APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. Data Types: The default Golang data types for decoding and encoding JSON are as follows: bool for JSON booleans. float64 for JSON numbers. string for JSON strings.
The json package always orders keys when marshalling. Specifically:
Maps have their keys sorted lexicographically
Structs keys are marshalled in the order defined in the struct
The implementation lives here ATM:
Gustavo Niemeyer gave great answer, just a small handy snippet I use to validate and reorder/normalize []byte representation of json when required
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With