Tomson
Tomson

Reputation: 13

Is there any way to unmarshal JSON into a map and preserve keys order

I need to unmarshal JSON data into the map by preserving the order of keys and values.

This is a JSON data example:

{
    "31ded736-4076-4b1c-b38f-7e8d9fa78b41": {
      "Name": "Requested",
      "Items": [
        { "ID": "c7ac5b7f-59b0-45e3-82fb-b3b0afc05f55", "GroupName": "First task" , "NumQuestion": "10" ,"Score":"10"},
        {"ID": "17acf9a1-b2c7-46c6-b975-759b9d9f538d", "GroupName": "Test1" , "NumQuestion": "20" ,"Score":"5" }
      ]
    },
    "115f7d04-3075-408a-b8ce-c6e46fe6053f": {
      "Name": "To do",
      "Items": [
        { "ID": "c7ac5b7f-59b0-45e3-82fb-b3b0afc05f56", "GroupName": "First task" , "NumQuestion": "5" ,"Score":"10"}
      ]
    },
    "9bcf1415-3a41-43b6-a871-8de1939a75c4": {
      "Name": "In Progress",
      "Items": [
        { "ID": "c7ac5b7f-59b0-45e3-82fb-b3b0afc05f57", "GroupName": "Second task" , "NumQuestion": "10" ,"Score":"5"}
      ]
    },
    "2f6c1455-6cf9-4009-b86b-de0a0d2204a1": {
      "Name": "Done",
      "Items": [
        { "ID": "c7ac5b7f-59b0-45e3-82fb-b3b0afc05f58", "GroupName": "Third task" , "NumQuestion": "20" , "Score":"7"}
      ]
    }
  }

This is my code:

var GroupTestListUpdate = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

    type Item struct {
        ID string `json:"id"`
        GroupName string `json:"groupName"`
        NumQuestion string `json:"numQuestion"`
        Score string `json:"score"`
    }

    type Input struct {
        Name string `json:"name"`
        Items []Item `array:"item"`
    }

    var objmap map[string]Input

    reqBody, err := ioutil.ReadAll(r.Body)
    if err != nil{
        http.Error(w, "can't read body", http.StatusBadRequest)
            return
    }

    json.Unmarshal(reqBody, &objmap)
    fmt.Println(objmap)
})

Output:

map[115f7d04-3075-408a-b8ce-c6e46fe6053f:{To do [{c7ac5b7f-59b0-45e3-82fb-b3b0afc05f56 First task 5 10}]} 2f6c1455-6cf9-4009-b86b-de0a0d2204a1:{Done [{c7ac5b7f-59b0-45e3-82fb-b3b0afc05f58 Third task 20 7}]} 31ded736-4076-4b1c-b38f-7e8d9fa78b41:{Requested [{c7ac5b7f-59b0-45e3-82fb-b3b0afc05f55 First task 10 10} {17acf9a1-b2c7-46c6-b975-759b9d9f538d Test1 20 5}]} 9bcf1415-3a41-43b6-a871-8de1939a75c4:{In Progress [{c7ac5b7f-59b0-45e3-82fb-b3b0afc05f57 Second task 10 5}]}]

Question:

  1. I want to know how to preserve the order of keys and values.
  2. I got the same output every time I tried this code, So I wonder that the order in the map is not completely random?

Upvotes: 0

Views: 923

Answers (1)

dolan
dolan

Reputation: 1804

Yes.

You can override the UnmarshalJSON method on a custom map type that will allow you to preserve the order.

As an example, here is a library that does just that: https://github.com/iancoleman/orderedmap.

Upvotes: 2

Related Questions