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.
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"`
}
While I personally would take the route JimB describes above another option is just to change how you display the data. I can infer based on your output that you did; fmt.Printf("%v", YourInstance)
. The order of the items in the map is irrelevant if you explicitly specify where each goes with a format string like;
fmt.Printf("red: %v, green: %v, blue: %v
", ColorInstance["red"], ColorInstance["green"], ColorInstance["blue"])
Now that only prints a single instance so to print the whole thing you'd need further logic but that's the basic idea.
If you want things in order, a map is not the structure for you. If you want quick access based on a key, then a map is a good choice. If you just want to format your output for writing to console or a file or whatever, it can be done easily with a map but personally I think, JimB's suggestion is the best way to approach deserializing and processing data like that. My philosophy is to make the structures as concrete as possible. You get the work out of the way up front and have cleaner, more concise, better performing code there after.