drfqfuhej48511519 2015-10-20 19:40
浏览 40
已采纳

Go中的排序界面

Been googling and stacking around for the solution with no success.

I'm importing a JSON file to an struct, however, when I want to use it, the values come out in a random order. This is an example of my JSON file:

"Assets": {
    "asset1": "asset1.png",
    "asset2": "asset2.png"
  },
  "Colors": {
    "MainColor": [
      {
        "red": 247,
        "green": 0,
        "blue": 247
      }
    ],
    "MainGradient": [
      {
        "red": 9,
        "green": 103,
        "blue": 170
      },
      {
        "red": 18,
        "green": 138,
        "blue": 221
      }
    ]
}

I can import the JSON using Unmarshal, however, when I print it, the "red, green,blue" values outputs in random order, like this:

[{map[asset1:asset1.png asset2:asset2.png] {[map[red:247 green:0 blue:247]] [map[green:103 red:9 blue:170] map[green:138 blue:221 red:18]]}}]

As you can see, the RGB values come at random order every time. I want to know if there's a way to always output the in the same order: red, green, blue.

Thank you.

  • 写回答

2条回答 默认 最新

  • douchui3933 2015-10-20 19:46
    关注

    Maps are unordered, both in Go and per the JSON spec. You will have to call them in order as you need them.

    r, g, b := color["red"], color["green"], color["blue"]
    

    You can also unmarshal the values into a struct, which will give you a deterministic layout:

    type Color struct {
        Red   int `json:"red"`
        Green int `json:"green"`
        Blue  int `json:"blue"`
    }
    

    http://play.golang.org/p/0l01NxJ4dq

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题