SoFunction
Updated on 2025-03-01

How to generate ordered json data in Golang map

Preface

This article mainly introduces relevant content about the generation of ordered json data from Golang map. It is shared for your reference and learning. Let’s take a look at the detailed introduction together:

Let’s first look at a piece of code that generates json in Golang, and first define amap[string]interface{}variable, and then save some values. Here, you should note that the previews field is in order. In order for the json data obtained by the browser to be ordered, amap[int]map[string]stringThe type is added with a key indicating 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, _ := (detail["game_tags"])
list["game_tags"] = (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
 
("test list:", list)

But in fact, for Golang, the previews field does not become ordered, and you can know it by printing, but the browser will automatically sort the json data with the int-type primary key, thus achieving the goal.

The generated json format data is as follows, arranged from small to large according to int:

{
 "data": {
  "game_desc": "As far as scholars go, how many ranks can you finally be ranked in? In order to fulfill your father's last wish, you embarked on this long road of promotion. What kind of person will you become in the end?",
  "game_logo": "/game/gameIcon/181/90681/icon_200.jpg?1472698847",
  "game_name": "How many ranks are you in the official position",
  "game_tags": [
   "hehe"
  ],
  "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
}

This has a disadvantage. It could have output a more concise data structure, but because of the disorder of maps, a primary key has to be added, which adds trouble to front-end parsing.

Summarize

The above is the entire content of this article. I hope that the content of this article will be of some help to everyone’s learning or using Go. If you have any questions, you can leave a message to communicate. Thank you for your support.