Go语言复合数据类型之JSON

209 阅读2分钟

JSON

JSON是JavaScript对象的表示法,是一种发送和接收信息的格式标准。也是我们日常工作中使用最为广泛的数据结构之一。

Go语言通过标准库encoding/json,encoding.xml,encoding/asn1和其他库对JSON的解码和编码做了很好的支持,这些库都拥有相同的API。我们在实例中使用最多的encoding/json来做演示。

JSON的对象用来编码Go里面的map(键为字符串类型)和结构体,如下:

 boolean true
 number -25.3
 string "hello"
 array ["pink","red","gray"]    
 object {
     "year":2021,
     "event":"victry",
     "medals":["gold","sliver","bronze"]
 }

示例

假设我们需要编写一个程序用来收集电影的观看次数并提供推荐,这个程序的Movie类型和典型元素列表如下:

 type Movie struct{
     Title string
     year int `json:"released"`
     Color bool `json:"color,omiy"`
     Actors []string       
     
 }
 ​
 var Movies = []Movies{
     {Title:"vdfv",Year:1956,Color:true,Actors:[]string{"Tom","Boob"}},
     {Title:"Luke",Year:1956,Color:true,Actors:[]string{"Lily"}},
     {Title:"Bullitt",Year:1956,Color:true,Actors:[]string{"David"}},
 }

这种类型的数据结构体最适合JSON,无论是从Go对象转为JSON还是从JSON转换为Go对象。把Go的数据结构,如Movies转换为JSON称为marshalmarshal是通过json.marshal来实现的。

 package main
 ​
 import (
     "encoding/json"
     "fmt"
     "log"
 )
 ​
 type Movie struct {
     Title  string
     Year   int  `json:"released"`
     Color  bool `json:"color,omiy"`
     Actors []string
 }
 ​
 var movie = []Movie{
     {Title: "vdfv", Year: 1956, Color: true, Actors: []string{"Tom", "Boob"}},
     {Title: "Luke", Year: 1956, Color: true, Actors: []string{"Lily"}},
     {Title: "Bullitt", Year: 1956, Color: true, Actors: []string{"David"}},
 }
 ​
 func main() {
 ​
     marshal, err := json.Marshal(movie)
     if err != nil {
         log.Fatalln("JSON marshaling was failed %s", marshal)
     }
     fmt.Printf("%s\n", marshal)
 }
    

movie通过以上代码转换为JSON的结果如下所示:

image.png 但是控制打印的JSON并不是很好阅读,因为它很长,所以我们使用json.MarchalIndent()方法,就可以在控制台输出格式化的JSON文本。json.MarchalIndent()方法有三个参数,第一个为我们需要转换的结构体,第二个是每行输出的前缀字符串,这里我们设为“”即可,第三个参数为定义字符串的缩进。

更改后的代码如下:

 package main
 ​
 import (
     "encoding/json"
     "fmt"
     "log"
 )
 ​
 type Movie struct {
     Title  string
     Year   int  `json:"released"`
     Color  bool `json:"color,omiy"`
     Actors []string
 }
 ​
 var movie = []Movie{
     {Title: "vdfv", Year: 1956, Color: true, Actors: []string{"Tom", "Boob"}},
     {Title: "Luke", Year: 1956, Color: true, Actors: []string{"Lily"}},
     {Title: "Bullitt", Year: 1956, Color: true, Actors: []string{"David"}},
 }
 ​
 func main() {
 ​
     marshal, err := json.MarshalIndent(movie,"","   ")
     if err != nil {
         log.Fatalln("JSON marshaling was failed %s", marshal)
     }
     fmt.Printf("%s\n", marshal)
 }
 ​

程序运行结果如下:

image.png 以上就是关于对JSON相关内容的介绍,希望可以帮助到你。

qrcode_for_gh_3fe38a18d553_258.jpg