0

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.

2 Answers2

2
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

mkopriva
  • 35,176
  • 4
  • 57
  • 71
0

Go is a statically typed language.

An empty interface may hold values of any type. But your nested list has no type.

Before

[{sub1  :sub1_score, sub2  :sub2_score}]

After

[]map[string]interface{}{
    {
        sub1: sub1_score,
        sub2: sub2_score,
    },
}
medasx
  • 634
  • 4
  • 7