Go利⽤map组合json格式数据当你需要⾃定义json格式请求时,⼜不想通过结构体实现时,可以尝试通过map组合实现:
package main
import (
"fmt"
"encoding/json"
"time"
)
// 利⽤map组合json格式数据
func BuildJsonData() {
req := make(map[string]interface{})
req["City"] = "Beijing"
req["PostCode"] = 100000
req["Timestamp"] = time.Now().Unix()
req["StudentInfo"] = map[string]interface{}{
"School": "Tsinghua University",
"Class": "test",
"StudentInfo": map[string]interface{}{
"Name": "Bill",
"Age": 25,
"Sex": "male",
},
}
byteReq, err := json.Marshal(req)
if err != nil {
fmt.Println("json.Marshal err.")
return
}
fmt.Println(string(byteReq))
}
func main() {
BuildJsonData()
}
/* 输出如下:
{
"City": "Beijing",
"PostCode": 100000,
"StudentInfo": {
"Class": "test",
"School": "Tsinghua University",
"StudentInfo": {
"Age": 25,
"Name": "Bill",
"Sex": "male"
}
},
"Timestamp": 1604556065
}
*/
另外,想要利⽤反引号 "`" 构造更为复杂的多层嵌套json数据,⽰例如下:
func Example {
// 正确:
urInfo := `{
"City": "Beijing",
"PostCode:": 100000,
"StudentInfo": {
"School": "Tsinghua University",
"Class": "test",
"StudentInfo": {
"Name": "Bill",
"Age": 25,
"Sex": "male"
}
},
"Timestamp": "123456789"
}`
// 带数组 [] 的⽰例:
urInfo := `{
"City": "Beijing",
"PostCode:": 100000,
"StudentInfo": {
"School": "Tsinghua University",
"Class": "test",
"StudentInfo":
[
{
"Name": "Bill",
"Age": 25
},
{
"Name": "Bill's brother",
"Age": 52
}
]
},
"Timestamp": "123456789"
}`
// 错误⽰例:
// urInfo := `{
/
/ "City": "Beijing",
// "PostCode:": 100000,
// "StudentInfo": {
// "School": "Tsinghua University",
// "Class": "test",
// "StudentInfo": {
// "Name": "Bill",
// "Age": 25,
// "Sex": "male"
// }, // error: 当前json及其⼦json结构内的最后⼀个字段末尾不加 ",". // } // 这⾏末尾要加",".
// "Timestamp": "123456789"
/
/ }`
}