Issue
I am trying to create a map of key values and then json.Marshal it before making an HTTP post request in Go/Golang
jsonData
{"name":"bob",
"stream":"science",
"grades":[{"maths" :"A+",
"science" :"A"}]
}
The structure of the map is like, it has string typed keys and values are strings and a slice and the slice itself has a map. So in terms of python I want to make a dictionary which has key value pairs but last key’s value is a list and the list has a dictionary in it.
a part from code is this:
postBody, err := json.Marshal(map[string]interface{}{
"name":name,
"stream":stream,
"grades":[{sub1 :sub1_score,
sub2 :sub2_score}]
})
but failed to make this kind of complex map.
Solution
postBody, err := json.Marshal(map[string]interface{}{
"name": name,
"stream": stream,
"grades": []map[string]interface{}{{
sub1: sub1_score,
sub2: sub2_score,
}},
})
or, if you’d like to avoid having to retype map[string]interface{}
type Obj map[string]any
postBody, err := json.Marshal(Obj{
"name": name,
"stream": stream,
"grades": []Obj{{
sub1: sub1_score,
sub2: sub2_score,
}},
})
https://go.dev/play/p/WQMiE5gsx9w
Answered By – mkopriva
Answer Checked By – Pedro (GoLangFix Volunteer)