Auto sorting fields in map, json

(Ilyas Gaisin) #1

I have a problem.
I take rows from the database and write them to the map interface.
Then I convert it to JSON and send it to the client.

I need to keep the sequence of fields specified in the database.

I leave you are a piece of code.

    rows, _ := db.Query("SELECT * FROM table")
	cols, _ := rows.Columns()

	defer rows.Close()

    d:= make([]map[string]interface{}, 0)
	for rows.Next() {
		columns := make([]interface{}, len(cols))
		columnPointers := make([]interface{}, len(cols))
		for i, _ := range columns {
			columnPointers[i] = &columns[i]


		m := make(map[string]interface{})
		for i, colName := range cols {
			val := columnPointers[i].(*interface{})
			m[colName] = *val

		d = append(d, m)
	jsData, _ := json.Marshal(d)
	w.Header().Set("Content-Type", "application/json")

( Kvaz1r) #2

Standart map is unordered -

A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type.

You should use ordered collecton like this one

(Norbert Melzer) #3


Neither gos map, nor json objects are ordered. {"a": 1, "b": 2} and {"b": 2, "a": 1} in JSON are equivalent.

(Ilyas Gaisin) #4

because I bring the data into a dynamic table by looping through everything in a loop. The table has about 100 fields.
To do this manually is not realistic.

(Norbert Melzer) #5

The proper way is to have some extra data point that describes the order of fields, eg a list of strings. Iterate over that list and use it to access the fields in the map/object.

(Ilyas Gaisin) #6

if the name of the fields are written in cyrillic with spaces?

(Norbert Melzer) #7

Why should that be a problem on the go side? Perhaps when trying to use them as column names in your database…

(K.S. Bhaskar) #8

Try storing the data you retrieve as “local” variables in YottaDB. The data is always sorted. See for more information. For what it’s worth, YottaDB also has a hierarchical key-value database / persistence engine (called “global” variables), but if you already have a database, you can just store the retrieved data in YottaDB without using the persistence engine.

Full disclosure: I lead YottaDB ( &

– Bhaskar