How does Golang map generate ordered json data detail

  • 2020-06-07 04:40:50
  • OfStack


This paper mainly introduces the related content of Golang map to generate orderly json data, and shares it for your reference and study. The following is a detailed introduction:

Let's start with a section of Golang's code to generate json. First, we define one map[string]interface{} Note that the previews field is defined in order for the json data obtained by the browser to be ordered map[int]map[string]string Type of, plus 1 key to indicate the order:

list := make(map[string]interface{})
list["id"] = detail["id"]
list["game_name"] = detail["game_name"]
list["game_logo"] = detail["game_m_logo"]
gameTags, _ := utils.InterfaceToStr(detail["game_tags"])
list["game_tags"] = strings.Split(gameTags, ",")
list["game_desc"] = detail["game_long_desc"]
list["play_total_times"] = 33333
testImages := make(map[int]map[string]string)
testImages[1] = map[string]string{"video": "xxx"}
testImages[2] = map[string]string{"image": "yyy1"}
testImages[3] = map[string]string{"image": "yyy2"}
testImages[5] = map[string]string{"image": "yyy5"}
testImages[4] = map[string]string{"image": "yyy3"}
list["previews"] = testImages
fmt.Println("test list:", list)

In fact, for Golang, the previews field is not therefore ordered, as you can tell by printing, but the browser automatically sorts the json data with the int type primary key, thus achieving the goal.

The generated DATA in json format is as follows, arranged from small to large by int:

 "data": {
  "game_desc": " From the show just 1 How many things will you end up with?   You have embarked on the long road to higher office in order to fulfill your father's last wish.   What will you eventually become?  ",
  "game_logo": "",
  "game_name": " In a few items ",
  "game_tags": [
   " Ha ha "
  "id": "3",
  "play_total_times": 33333,
  "previews": {
   "1": {
    "video": "xxx"
   "2": {
    "image": "yyy1"
   "3": {
    "image": "yyy2"
   "4": {
    "image": "yyy3"
   "5": {
    "image": "yyy5"
 "msg": "ok",
 "result": 0

The downside is that you could have produced a simpler data structure, but because of the disorder of map you had to add a primary key, which made front-end parsing more difficult.


Related articles: