在 go 中制作具有不同数据类型的地图,以便使用 json 数据发出 post 请求

make a map with different data types in go for making post request with json data

我正在尝试创建键值映射,然后在 Go/Golang

中发出 HTTP post 请求之前 json.Marshal 它

jsonData

{"name":"bob",
"stream":"science",
"grades":[{"maths"    :"A+",
           "science"  :"A"}]
}

映射的结构是这样的,它有字符串类型的键和值是字符串和一个切片,切片本身有一个映射。因此,就 python 而言,我想制作一个具有键值对的字典,但最后一个键的值是一个列表,该列表中有一个字典。

代码的一部分是这样的:

postBody, err := json.Marshal(map[string]interface{}{
        "name":name,
        "stream":stream,
        "grades":[{sub1  :sub1_score,
                   sub2  :sub2_score}]
        })

但是没能做出这种复杂的地图

Go 是一种静态类型语言。

空接口可以包含任何类型的值。但是你的嵌套列表没有类型。

之前

[{sub1  :sub1_score, sub2  :sub2_score}]

之后

[]map[string]interface{}{
    {
        sub1: sub1_score,
        sub2: sub2_score,
    },
}
postBody, err := json.Marshal(map[string]interface{}{
    "name":   name,
    "stream": stream,
    "grades": []map[string]interface{}{{
        sub1: sub1_score,
        sub2: sub2_score,
    }},
})

或者,如果您想避免重新输入 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