Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce JSON with sorted keys in Go?

Tags:

json

go

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?

like image 819
sheki Avatar asked Sep 07 '13 01:09

sheki


People also ask

How do I sort a JSON key?

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.

Can JSON be sorted?

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.

What is JSON decoder in Golang?

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.


2 Answers

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:

  • http://golang.org/src/pkg/encoding/json/encode.go?#L359
like image 141
Gustavo Niemeyer Avatar answered Sep 21 '22 19:09

Gustavo Niemeyer


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 } 
like image 39
Radek 'Goblin' Pieczonka Avatar answered Sep 23 '22 19:09

Radek 'Goblin' Pieczonka