💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# GO TYPES JSON # Author 品茶 > JavaScript对象表示法JSON是一种用于发送和接收结构变化信息的标准协议,由于其简洁性、可读性、流行程序等原因,JSON是应用最广泛的一个。 > GO语言encoding/json就是处理此协议的。 > json类型 字符串、数字、布尔值、 数组和字典 > true false unicode [] {} > 编码marshaling默认使用GO语言的反射reflect技术,只有导出的结构体成员才会被编码。 > 成员体tag > Year int `json:"released"` // 关联到成员的元信息字符串released > Color bool `json:"color,omitempty"` // omitempty 当成员为空或零值时不生成JSON对象 > 解码unmarshaling ~~~ //定义一个结构体 但是用了json的一些东西 type Movie struct { Title string `json:"title"` Year int `json:"released"` Color bool `json:"color,omitempty"` // omitempty无值为空 Actors []string `json:"actors"` // []string } func main() { movies := []Movie{ { Title: "Casablanca", Year: 1942, Color: false, Actors: []string{ "a", "b", "c", }, }, { Title: "yueguangbaohe", Year: 2006, Color: true, Actors: []string{ "Zhouxingchi", "liutao", "Huangguanzhong", }, }, } fmt.Printf("%#v\n", movies) //编码 marshaling json.Marshal //data, err := json.Marshal(movies) // 转成一行 data, err := json.MarshalIndent(movies, "", " ") // 转成格式化的字符串 if err != nil { log.Fatalf("Json marshaling failed: %s", err) } fmt.Printf("%s\n", data) // %s // 解码 ms := []Movie{} err = json.Unmarshal(data, &ms) if err != nil { log.Fatalf("Json unmarshaling failed: %s", err) } fmt.Printf("%#v\n", ms) } ~~~