Go利用map组合json格式数据

更新时间:2023-05-11 12:55:19 阅读: 评论:0

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"
/
/ }`
}

本文发布于:2023-05-11 12:55:19,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/585550.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:格式   末尾   数据   组合   实现   想要   引号
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图