【GO】切片转json

简介: 【GO】切片转json

咔咔博客之切片转json

结构体转jsonmap转json中我们都说了一个函数那就是json_Marshal函数。同样这个函数也可以对切片进行转json

案例

image.png

func main() {
  strings := []string{"咔咔博客", "咔咔手赚网"}
  bytes, e := json.Marshal(strings)
  if e != nil {
    fmt.Println("序列化失败")
  } else {
    s := string(bytes)
    // ["咔咔博客","咔咔手赚网"]
    fmt.Println(s)
  }
}

屏幕快照 2022-05-18 下午11.11.54.png

func main() {
  // 在切片里边定义map类型
  mSlice := make([]map[string]interface{}, 0)
  mSlice = append(mSlice, map[string]interface{}{"name": "咔咔"})
  mSlice = append(mSlice, map[string]interface{}{"name": "咔咔手赚网"})
  mSlice = append(mSlice, map[string]interface{}{"name": "咔咔博客"})
  bytes, e := json.Marshal(mSlice)
  if e != nil {
    fmt.Println("序列化失败")
  } else {
    s := string(bytes)
    // [{"name":"咔咔"},{"name":"咔咔手赚网"},{"name":"咔咔博客"}]
    fmt.Println(s)
  }
}

案例总结

无论是map、结构体、切片转json都是用json_Marchil()这个函数进行json的序列化



相关文章
|
4月前
|
Go
go语言数组与切片
go语言数组与切片
|
6天前
|
Go 索引
Go to Learn Go之切片
Go to Learn Go之切片
13 1
|
8天前
|
编译器 Go 索引
Go数组、多维数组和切片(动态数组),及常用函数len(),cap(),copy(),append()在切片中的使用
本文介绍了Go语言中数组、多维数组和切片(动态数组)的基本概念和操作,包括数组的定义、初始化、访问,多维数组的定义和访问,以及切片的创建、使用和扩容。同时,还讲解了切片中常用的函数len()、cap()、copy()和append()的使用方法。
|
2月前
|
JSON 人工智能 编译器
Go json 能否解码到一个 interface 类型的值
Go json 能否解码到一个 interface 类型的值
26 1
|
2月前
|
Go
Go 1.21的新特性: 切片和映射
Go 1.21的新特性: 切片和映射
|
2月前
|
JSON Go 数据格式
Go - json.Unmarshal 遇到的小坑
Go - json.Unmarshal 遇到的小坑
46 9
|
2月前
|
存储 Go
go 切片长度与容量的区别
go 切片长度与容量的区别
|
2月前
|
存储 缓存 Go
在 Go 中如何复制切片和映射?
【8月更文挑战第31天】
43 0
|
2月前
|
存储 Go 数据处理
C 数组和 Go 切片的区别详解
【8月更文挑战第31天】
30 0
|
2月前
|
JSON Go 数据格式
Go实现json字符串与各类struct相互转换
文章通过Go语言示例代码详细演示了如何实现JSON字符串与各类struct之间的相互转换,包括结构体对象生成JSON字符串和JSON字符串映射到struct对象的过程。
15 0
下一篇
无影云桌面